Skip to content

Latest commit

 

History

History
83 lines (58 loc) · 1.91 KB

File metadata and controls

83 lines (58 loc) · 1.91 KB

English Version

题目描述

给你一个矩阵 mat,其中每一行的元素都已经按 严格递增 顺序排好了。请你帮忙找出在所有这些行中 最小的公共元素

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

 

示例:

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

 

提示:

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

解法

“计数器”实现。

Python3

class Solution:
    def smallestCommonElement(self, mat: List[List[int]]) -> int:
        counter = collections.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;
    }
}

...