Search a 2D Matrix

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.

解法:由於矩陣每一行的末尾數字都小於下一行的開頭數字,並且每行都有序,因此我們可以把矩陣當做一個一維數組,長度爲row*column,在有序的一位數組中,採用Binary Search來查找target.

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0) {
            return false;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int left = 0;
        int right = row*col - 1;
        while(left <= right) {
            int mid = left + (right - left)/2;
            if(matrix[mid/col][mid%col] == target) {
                return true;
            }
            else if(matrix[mid/col][mid%col] > target) {
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
        }
        return false;
    }
}

注意:對於一個row*column的矩陣,某元素matrix[x][y]轉化成一維數組a中對應元素爲a[x*row+y];相反的,將一維數組某元素a[x]轉化爲矩陣即爲matrix[x/column][x%column].

發佈了66 篇原創文章 · 獲贊 17 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章