Skip to content

Files

Latest commit

f385924 · Apr 29, 2022

History

History
92 lines (65 loc) · 2.14 KB

File metadata and controls

92 lines (65 loc) · 2.14 KB

English Version

题目描述

给你一个 m x n 的矩阵 mat,其中每一行的元素均符合 严格递增 。请返回 所有行中的 最小公共元素 

如果矩阵中没有这样的公共元素,就请返回 -1

 

示例 1:

输入:mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
输出:5

示例 2:

输入:mat = [[1,2,3],[2,3,4],[2,3,5]]
输出: 2

 

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 500
  • 1 <= mat[i][j] <= 104
  • mat[i] 已按严格递增顺序排列。

解法

“计数器”实现。

Python3

class Solution:
    def smallestCommonElement(self, mat: List[List[int]]) -> int:
        counter = Counter()
        for row in mat:
            for num in row:
                counter[num] += 1
                if counter[num] == len(mat):
                    return num
        return -1

Java

class Solution {
    public int smallestCommonElement(int[][] mat) {
        int[] counter = new int[10001];
        for (int[] row : mat) {
            for (int num : row) {
                ++counter[num];
                if (counter[num] == mat.length) {
                    return num;
                }
            }
        }
        return -1;
    }
}

...