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 }