返回介绍

solution / 1100-1199 / 1198.Find Smallest Common Element in All Rows / README_EN

发布于 2024-06-17 01:03:22 字数 3581 浏览 0 评论 0 收藏 0

1198. Find Smallest Common Element in All Rows

中文文档

Description

Given an m x n matrix mat where every row is sorted in strictly increasing order, return _the smallest common element in all rows_.

If there is no common element, return -1.

 

Example 1:

Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output: 5

Example 2:

Input: mat = [[1,2,3],[2,3,4],[2,3,5]]
Output: 2

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 500
  • 1 <= mat[i][j] <= 104
  • mat[i] is sorted in strictly increasing order.

Solutions

Solution 1: Counting

We use an array $cnt$ of length $10001$ to count the frequency of each number. We sequentially traverse each number in the matrix and increment its frequency. When the frequency of a number equals the number of rows in the matrix, it means that this number appears in each row, and thus it is the smallest common element. We return this number.

If we do not find the smallest common element after the traversal, we return $-1$.

The time complexity is $O(m \times n)$, and the space complexity is $O(10^4)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively.

class Solution:
  def smallestCommonElement(self, mat: List[List[int]]) -> int:
    cnt = Counter()
    for row in mat:
      for x in row:
        cnt[x] += 1
        if cnt[x] == len(mat):
          return x
    return -1
class Solution {
  public int smallestCommonElement(int[][] mat) {
    int[] cnt = new int[10001];
    for (var row : mat) {
      for (int x : row) {
        if (++cnt[x] == mat.length) {
          return x;
        }
      }
    }
    return -1;
  }
}
class Solution {
public:
  int smallestCommonElement(vector<vector<int>>& mat) {
    int cnt[10001]{};
    for (auto& row : mat) {
      for (int x : row) {
        if (++cnt[x] == mat.size()) {
          return x;
        }
      }
    }
    return -1;
  }
};
func smallestCommonElement(mat [][]int) int {
  cnt := [10001]int{}
  for _, row := range mat {
    for _, x := range row {
      cnt[x]++
      if cnt[x] == len(mat) {
        return x
      }
    }
  }
  return -1
}
function smallestCommonElement(mat: number[][]): number {
  const cnt: number[] = new Array(10001).fill(0);
  for (const row of mat) {
    for (const x of row) {
      if (++cnt[x] == mat.length) {
        return x;
      }
    }
  }
  return -1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文