|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: |
| 4 | + * 74. Search a 2D Matrix |
| 5 | + * |
| 6 | + * Write an efficient algorithm that searches for a value in an m x n matrix. |
| 7 | + * This matrix has the following properties: |
5 | 8 |
|
6 | 9 | Integers in each row are sorted from left to right.
|
7 | 10 | The first integer of each row is greater than the last integer of the previous row.
|
|
21 | 24 | public class _74 {
|
22 | 25 |
|
23 | 26 | public boolean searchMatrix(int[][] matrix, int target) {
|
24 |
| - if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; |
25 |
| - int m = matrix.length, n = matrix[0].length; |
26 |
| - if (target < matrix[0][0] || target > matrix[m-1][n-1]) return false; |
27 |
| - //just treat it as a sorted list |
| 27 | + if (matrix == null || matrix.length == 0 |
| 28 | + || matrix[0].length == 0 |
| 29 | + || matrix[0][0] > target |
| 30 | + || matrix[matrix.length-1][matrix[0].length-1] < target) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + int m = matrix.length; |
| 34 | + int n = matrix[0].length; |
28 | 35 | int left = 0;
|
29 |
| - int right = m*n - 1; |
30 |
| - while (left != right) { |
31 |
| - int mid = (left + right - 1) >> 1; |
32 |
| - if (matrix[mid/n][mid%n] < target) left = mid + 1; |
33 |
| - else right = mid; |
| 36 | + int right = m * n - 1 ; |
| 37 | + while (left <= right) { |
| 38 | + int mid = left + (right-left)/2; |
| 39 | + int row = mid/n; |
| 40 | + int col = mid%n; |
| 41 | + if (matrix[row][col] == target) { |
| 42 | + return true; |
| 43 | + } else if (matrix[row][col] > target) { |
| 44 | + right = mid-1; |
| 45 | + } else { |
| 46 | + left = mid+1; |
| 47 | + } |
34 | 48 | }
|
35 |
| - return matrix[right/n][right%n] == target; |
| 49 | + return false; |
36 | 50 | }
|
37 |
| - |
38 | 51 | }
|
0 commit comments