74. Search a 2D Matrix

来源:互联网 发布:js重新加载div 编辑:程序博客网 时间:2024/05/16 23:49

Difficulty: Medium
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.

采用内外嵌套二分查找的方式
外循环二分查找到存在的哪一行
内循环二分查找target

bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {    int low_row = 0, high_row = matrixRowSize-1, low_col = 0, high_col = matrixColSize-1;    int mid_row, mid_col;    while(low_row <= high_row) {        mid_row = (low_row + high_row)/2;        if(target >= matrix[mid_row][0] && target <= matrix[mid_row][matrixColSize-1]) {            while(low_col <= high_col) {                mid_col = (low_col+high_col)/2;                if (target == matrix[mid_row][mid_col]) return true;                else if (target < matrix[mid_row][mid_col]) {                    high_col = mid_col - 1;                } else {                    low_col = mid_col + 1;                }            }            return false;        } else if(target > matrix[mid_row][matrixColSize-1]) {            low_row = mid_row+1;        } else {            high_row = mid_row-1;        }    }    return false;}
0 0
原创粉丝点击