• [Swift]LeetCode1198. 找出所有行中最小公共元素 | Find Smallest Common Element in All Rows


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(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 }
  • 相关阅读:
    关于FPGA设计16位乘法器的两…
    const&nbsp;int&nbsp;*pi与int&amp;nbs…
    HTML5基础学习
    html5基础!!
    正确分析结构使用正确的HTML标签。CSS样式写一起。
    开发经验以及方法
    布局设计
    position定位
    浏览器的兼容性
    float浮动的世界
  • 原文地址:https://www.cnblogs.com/strengthen/p/11521672.html
Copyright © 2020-2023  润新知