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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =
3
, return true
.
先对矩阵的行数进行二分法查找, 找到target所在行数 再对此行二分法查找 来判断target时候存在。
这个的算法时间复杂度是O(log(rows)+log(columns))。
做这道题时候犯二了 在第一次二分法的时候先判断matrix[start][0] < target结果死活不对, 后来发现如果这么判定的话当matrix[end][0] < target 时候也会跳到start行。
做这道题时候犯二了 在第一次二分法的时候先判断matrix[start][0] < target结果死活不对, 后来发现如果这么判定的话当matrix[end][0] < target 时候也会跳到start行。
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0){ return false; } if (matrix[0] == null || matrix[0].length == 0){ return false; } int start = 0; int end = matrix.length - 1; int row; while (start + 1 < end){// find the row int mid = start + (end - start) / 2; if (matrix[mid][0] == target){ return true; } else if (matrix[mid][0] < target){ start = mid; } else { end = mid; } } if (matrix[end][0] <= target) { row = end; } else if (matrix[start][0] <= target) { row = start; } else { return false; } start = 0; end = matrix[0].length - 1; while (start + 1 < end){// find the column int mid = start + (end - start) / 2; if (matrix[row][mid] == target){ return true; } else if (matrix[row][mid] < target){ start = mid; } else { end = mid; } } if (matrix[row][start] == target){ return true; } else if (matrix[row][end] == target){ return true; } else { return false; } } }
把2d矩阵转换成1d 赋值start = 0 end = row * column -1
每个元素都可以用 matrix[position/column][position%column]来表示
然后用2分法解题
时间复杂度 O(log(row * column))
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0){ return false; } if (matrix[0] == null || matrix[0].length == 0){ return false; } int row = matrix.length; int column = matrix[0].length; int start = 0; int end = row * column - 1; while (start + 1 < end){ int mid = start + (end - start) / 2; int num = matrix[mid / column][mid % column]; if (num == target){ return true; } else if(num < target){ start = mid; } else { end = mid; } } if (matrix[start / column][start % column] == target){ return true; } else if (matrix[end / column][end % column] == target){ return true; } else { return false; } } }
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) { return false; } if (matrix[0] == null || matrix[0].length == 0) { return false; } int m = matrix.length; int n = matrix[0].length; int total = m * n; int start = 0; int end = total - 1; while (start <= end) { int mid = start + (end - start) / 2; if (matrix[mid/n][mid%n] == target) { return true; } else if (matrix[mid/n][mid%n] > target) { end = mid - 1; } else { start = mid + 1; } } return false; } }
没有评论:
发表评论