[LeetCode] 1198. Find Smallest Common Element in All Rows


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.

找出所有行中最小公共元素。

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-smallest-common-element-in-all-rows
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题我提供两种思路,一种是hashmap,一种是二分法。

首先是hashmap。我们利用一个hashmap统计这个二维矩阵里面所有的元素各自都出现了几次,最后再统计每个元素的出现次数,找出出现次数 = n 的最小的元素。

时间O(mn)

空间O(n)

Java实现

 1 class Solution {
 2     public int smallestCommonElement(int[][] mat) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         int m = mat.length;
 5         int n = mat[0].length;
 6         for (int i = 0; i < m; i++) {
 7             for (int j = 0; j < n; j++) {
 8                 map.put(mat[i][j], map.getOrDefault(mat[i][j], 0) + 1);
 9             }
10         }
11 
12         int min = Integer.MAX_VALUE;
13         for (int key : map.keySet()) {
14             if (map.get(key) == m) {
15                 min = Math.min(min, key);
16             }
17         }
18         return min == Integer.MAX_VALUE ? -1 : min;
19     }
20 }

 

二分法的做法是,针对第一行的每个元素,利用二分法在剩余的行里面找是不是存在,对于第一行的某个元素 i,如果他在某一行不存在了,则可以break,检查下一个元素。如果所有的元素都不满足条件则整个函数return false。

时间O(m * logn)

空间O(1)

Java实现

 1 class Solution {
 2     public int smallestCommonElement(int[][] mat) {
 3         int m = mat.length;
 4         int n = mat[0].length;
 5         for (int i : mat[0]) {
 6             boolean found = true;
 7             for (int j = 0; j < m; j++) {
 8                 if (!helper(mat[j], i)) {
 9                     found = false;
10                     break;
11                 }
12             }
13             if (found) {
14                 return i;
15             }
16         }
17         return -1;
18     }
19 
20     private boolean helper(int[] row, int target) {
21         int left = 0;
22         int right = row.length - 1;
23         while (left <= right) {
24             int mid = left + (right - left) / 2;
25             if (row[mid] > target) {
26                 right = mid - 1;
27             } else if (row[mid] < target) {
28                 left = mid + 1;
29             } else {
30                 return true;
31             }
32         }
33         return false;
34     }
35 }

 

LeetCode 题目总结


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM