Write an efficIEnt algorithm that searches for a value in an m x n matrix. This matrix has the following propertIEs:
Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.Example:
ConsIDer the following matrix:
[ [1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
Given target = 5
,return true
.
Given target = 20
,return false
.
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
每行的元素从左到右升序排列。 每列的元素从上到下升序排列。示例:
现有矩阵 matrix 如下:
[ [1,30]]
给定 target = 5
,返回 true
。
给定 target = 20
,返回 false
。
328ms
1 class Solution { 2 func searchmatrix(_ matrix: [[Int]],_ target: Int) -> Bool { 3 // start at top right 4 if matrix.count < 1 || matrix[0].count < 1 { return false } 5 6 let rows = matrix.count,cols = matrix[0].count 7 var r = 0,c = cols - 1 8 9 while c >= 0,r < rows {10 let num = matrix[r][c]11 if num == target {12 return true13 } else if num < target {14 r += 115 } else {16 c -= 117 }18 }19 20 return false21 }22 }
332ms
1 class Solution { 2 func searchmatrix(_ matrix: [[Int]],_ target: Int) -> Bool { 3 guard matrix.count > 0,matrix[0].count > 0 else { 4 return false 5 } 6 7 let m = matrix.count 8 let n = matrix[0].count 9 10 if target < matrix[0][0] || target > matrix[m-1][n-1] {11 return false12 }13 14 var i = m-1,j = 015 16 while i >= 0,j < n {17 if matrix[i][j] == target {18 return true19 } else if matrix[i][j] > target {20 i -= 121 } else {22 j += 123 }24 }25 26 return false27 }28 }
332ms
1 class Solution { 2 func searchmatrix(_ matrix: [[Int]],_ target: Int) -> Bool { 3 guard !matrix.isEmpty && !matrix[0].isEmpty else { 4 return false 5 } 6 7 var row = 0 8 var column = matrix[0].count - 1 9 while column >= 0 && row < matrix.count {10 if matrix[row][column] > target {11 column -= 112 } else if matrix[row][column] < target {13 row += 114 } else {15 return true16 }17 }18 19 return false20 }21 }
340ms
1 class Solution { 2 func searchmatrix(_ matrix: [[Int]],_ target: Int) -> Bool { 3 4 guard matrix.count > 0,matrix[0].count > 0 else { return false } 5 var m = matrix.count,n = matrix[0].count 6 var i = m-1,j = 0 7 while true { 8 if matrix[i][j] == target { return true } 9 else if matrix[i][j] < target { j += 1 }10 else {11 i -= 112 }13 if i < 0 || j >= n { return false }14 }15 return false16 }17 }
348ms
1 class Solution { 2 func searchmatrix(_ matrix: [[Int]],_ target: Int) -> Bool { 3 for i in 0..<matrix.count { 4 for j in strIDe(from: matrix[i].count,to: 0,by: -1) { 5 if matrix[i][j - 1] == target { 6 return true 7 } 8 } 9 }10 11 return false 12 }13 }总结
以上是内存溢出为你收集整理的[Swift]LeetCode240. 搜索二维矩阵 II | Search a 2D Matrix II全部内容,希望文章能够帮你解决[Swift]LeetCode240. 搜索二维矩阵 II | Search a 2D Matrix II所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)