74. Search a 2D Matrix&240. Search a 2D Matrix II

来源:互联网 发布:用户购买数据分析 编辑:程序博客网 时间:2024/06/07 14:30

74.

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.

考虑从0,0的位置找起,按行搜索,一旦找到一行target且下一行>target,就在本行内开始搜索,用二分搜索。

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {                int row=matrix.size();        int col=matrix[0].size();                //因为循环中要判断matrix[i+1][0],因此循环只执行到倒数第二行,对最后一行另行判断        for(int i=0;i<row-1;i++){            if(matrix[i][0]==target) return true;            else if(matrix[i][0]<target&&matrix[i+1][0]>target){                int left=0;                int right=col-1;                while(left>=0&&right<col&&left<=right){//这里一开始忘记加left和right的判断条件,left和right都不能越界且left必须<=right                    int mid=(left+right+1)/2;//+1是为了规避开0,1的情况                    if(matrix[i][mid]==target) return true;                    else if(matrix[i][mid]>target) right=mid-1;                    else left=mid+1;                }                                return false;            }        }                for(int j=0;j<col;j++)             if(matrix[row-1][j]==target) return true;                return false;    }};

240.

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.

一开始想递归……后来看看discuss发现用二叉搜索树更好,而且很快。

左下角的数字有一个特性,向上减小向右增大,因此可以从左下角开始检索,如果比target大就向上继续检索,比target小就向右检索

这里发现一个trick就是当要判断matrix[i][j]和target的大小时,因为matrix里大部分数字肯定都是不等于target的,因此==这个条件一定要放到最后。

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {                int row=matrix.size();        int col=matrix[0].size();        int r=row-1,c=0;                while(r>=0&&c<=col-1){            if(target>matrix[r][c]) c++;            else if(target<matrix[r][c]) r--;            else return true;        }                return false;    }};


0 0
原创粉丝点击