LeetCode240. Search a 2D Matrix II题解

来源:互联网 发布:用友软件供应商 编辑:程序博客网 时间:2024/05/26 17:48

题目描述

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 in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.

样例

For example, consider the following matrix:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true;
Given target = 20, return false.

解题思路:
在每行进行二分查找,耗时192ms 比直接暴力查快

bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {    int BinarySearch(int *array, int aSize, int key)    {        if ( array == NULL || aSize == 0 )            return -1;        int low = 0;        int high = aSize - 1;        int mid = 0;        while ( low <= high )        {            mid = (low + high )/2;            if ( array[mid] < key)                low = mid + 1;            else if ( array[mid] > key )                high = mid - 1;            else                return mid;        }        return -1;    }    int i,j,ans;    for(i=0;i<matrixRowSize;i++)    {        ans = BinarySearch(matrix[i],matrixColSize,target);        if(ans != -1)        {            return true;        }    }    return false;}

下面这种解法是看到别人的方法,时间复杂度更低。
上一种是从矩阵左上角开始的,这次从右上角开始。因为这是已经排序好的矩阵,比右上角小的只能在他左边(即行序号–),比右上角大的只能在他的下边(及列序号++)
代码如下:

bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {    if(matrixRowSize==0 || matrixColSize==0)         return false;     int i = 0,j = matrixColSize-1;    while(i<matrixRowSize && j>=0)     {          if(target == matrix[i][j])             return true;          else if(target < matrix[i][j])             --j;          else            ++i;      }      return false; }
原创粉丝点击