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.
Example
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
- Method1:从右上角开始遍历
- 如果temp大于target,左移。
- 如果temp小于target,下移。
- 如果等于,返回。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) return false;
int height = matrix.length;
int width = matrix[0].length;
int row = 0, col = width - 1;
while(row < height && col >= 0){
int temp = matrix[row][col];
if(temp == target) return true;
else if(temp < target)
row++;
else
col--;
}
return false;
}
}
这道题还是比较经典,二刷的完全可以记住一刷的结果。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int height = matrix.length, width = matrix[0].length;
int col = width - 1, row = 0;
while(row < height && col >= 0){
if(matrix[row][col] == target) return true;
else if(matrix[row][col] > target) col--;
else row++;
}
return false;
}
}
- Method 1: Binary Search, AC 100%
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int height = matrix.length, width = matrix[0].length; int row = 0; while(row < height && target > matrix[row][width - 1]){ row++; } return row >= height ? false: bs(matrix[row], 0, width - 1, target); } private boolean bs(int[] nums, int low, int high, int target){ if(low > high) return false; int mid = low + (high - low) / 2; if(target == nums[mid]) return true; else if(target > nums[mid]) return bs(nums, mid + 1, high, target); else return bs(nums, low, mid - 1, target); } }
- Method 1: search
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int height = matrix.length, width = matrix[0].length; int x = 0, y = width - 1; while(x >= 0 && x < height && y >= 0 && y < width){ if(matrix[x][y] == target) return true; else if(matrix[x][y] < target){ x++; }else{ y--; } } return false; } }