在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
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 = Given target = 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
示例: 现有矩阵 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] ] 给定 target = 给定 target = 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 }
|
请发表评论