題目要求
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
.
分析
一開始寫的時候把他拆分成了兩個二分查找,先縱向找,再橫向找。縱向的二分查找比較復雜,要確定是在某個坐標上,或者在兩個坐標之間。
后來找到一個更好的方法,就是把二維數組的坐標轉化成一位數組,整體進行二分查找,程序更簡單,復雜度也更低了。
Java代碼
public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0) { return false; } int xLength = matrix[0].length; int min = 0; int max = matrix[0].length * matrix.length - 1; int x, y, current; while (min <= max) { current = (min + max) / 2; y = current / xLength; x = current % xLength; if (matrix[y][x] == target) { return true; } else if (target < matrix[y][x]) { max = current - 1; } else { min = current + 1; } } return false; }