[leetcode-74]Search a 2D Matrix(c)

来源:互联网 发布:p2p下载软件哪个好 编辑:程序博客网 时间:2024/05/17 23:15

问题描述:
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.

分析:搜索矩阵,而且矩阵有很大特点。每行增大,而且下一行大于上一行的最后一个值。那么把矩阵放平那就是一个有序的数组。显然用二分查找很容易找到,时间复杂度为O(log(N*M))
其实这道题还有另外一种解法,不过时间复杂度为O(m+n)。根据特点:
每行递增,每列递增。那么从右上角开始出发,如代码2所示:

代码如下:4ms

bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {    int right = matrixRowSize*matrixColSize-1;    int left = 0;    while(left<=right){        int mid = (left+right)/2;        int row = mid/matrixColSize;        int col = mid%matrixColSize;        if(matrix[row][col]==target)            return true;        else if(matrix[row][col]<target)            left = mid+1;        else             right = mid-1;    }    return false;}

代码2如下:4ms

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