Search a 2D Matrix | & II
Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.
This matrix has the following properties:
- Integers in each row are sorted from left to right.
- Integers in each column are sorted from up to bottom.
- No duplicate integers in each row or column.
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
Given target = 3, return 2.
分析:
因为数组里的数有上面三个特性,所以我们可以从左下角开始找。如果当前值比target大,明显往上走,比target小,往右走 (其它角没有这样的性质),如果一样斜上走。Time complexity: (O(m + n)) (m = matrix.length, n = matrix[0].length)
1 public class Solution { 7 public int searchMatrix(int[][] matrix, int target) { 8 // check corner case 9 if (matrix == null || matrix.length == 0 || matrix[].length == 0) { 10 return 0; 11 } 16 // from bottom left to top right 17 int x = matrix.length - 1; 18 int y = 0; 19 int count = 0; 20 21 while (x >= 0 && y < matrix[0].length) { 22 if (matrix[x][y] < target) { 23 y++; 24 } else if (matrix[x][y] > target) { 25 x--; 26 } else { 27 count++; 28 x--; 29 y++; 30 } 31 } 32 return count; 33 34 } 35 }
Search a 2D Matrix I
Write an efficient algorithm that searches for a value in an mx 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
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
分析:
根据数组的特点,我们需要找出一个大范围(row),然后再确定小范围。
1 public class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; 4 int rowCount = matrix.length, colCount = matrix[0].length; 5 if (matrix[0][0] > target || matrix[rowCount - 1][colCount - 1] < target) return false; 6 7 int row = getRowNumber(matrix, target); 8 int column = getColumnNumber(matrix, row, target); 9 10 return matrix[row][column] == target; 11 12 } 13 14 public int getRowNumber(int[][] matrix, int target) { 15 int start = 0, end = matrix.length - 1, width = matrix[0].length; 16 while (start <= end) { 17 int mid = start + (end - start) / 2; 18 if (matrix[mid][width - 1] == target) { 19 return mid; 20 } else if (matrix[mid][width - 1] > target) { 21 end = mid - 1; 22 } else { 23 start = mid + 1; 24 } 25 } 26 return start; 27 } 28 29 public int getColumnNumber(int[][] matrix, int row, int target) { 30 int start = 0, end = matrix[0].length; 31 32 while (start <= end) { 33 int mid = start + (end - start) / 2; 34 if (matrix[row][mid] == target) { 35 return mid; 36 } else if (matrix[row][mid] > target) { 37 end = mid - 1; 38 } else { 39 start = mid + 1; 40 } 41 } 42 return start; 43 } 44 }

浙公网安备 33010602011771号