★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公眾號:山青詠芝(let_us_code)
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11521672.html
➤如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a matrix mat
where every row is sorted in 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
Constraints:
1 <= mat.length, mat[i].length <= 500
1 <= mat[i][j] <= 10^4
mat[i]
is sorted in increasing order.
給你一個矩陣 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]
已按遞增順序排列。
1 class Solution { 2 func smallestCommonElement(_ mat: [[Int]]) -> Int { 3 let n:Int = mat.count 4 var ps:[Int] = [Int](repeating:0,count:n) 5 let m:Int = mat[0].count 6 outer: 7 for i in 0..<m 8 { 9 for j in 1..<n 10 { 11 while(ps[j] < m && mat[j][ps[j]] < mat[0][i]) 12 { 13 ps[j] += 1 14 } 15 if ps[j] < m && mat[j][ps[j]] == mat[0][i] 16 { 17 continue 18 } 19 else 20 { 21 continue outer 22 } 23 } 24 return mat[0][i] 25 } 26 return -1 27 } 28 }