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 true 13 } else if num < target { 14 r += 1 15 } else { 16 c -= 1 17 } 18 } 19 20 return false 21 } 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 false 12 } 13 14 var i = m-1,j = 0 15 16 while i >= 0,j < n { 17 if matrix[i][j] == target { 18 return true 19 } else if matrix[i][j] > target { 20 i -= 1 21 } else { 22 j += 1 23 } 24 } 25 26 return false 27 } 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 -= 1 12 } else if matrix[row][column] < target { 13 row += 1 14 } else { 15 return true 16 } 17 } 18 19 return false 20 } 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 -= 1 12 } 13 if i < 0 || j >= n { return false } 14 } 15 return false 16 } 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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。