[LeetCode] 74, a two-dimensional search matrix

Title Description

Prepared by an efficient algorithm to determine the m X n- matrix, the presence or absence of a target value. This matrix has the following characteristics:

  • An integer of from left to right in each row in ascending order.
  • The first integer is greater than the last row of each integer previous row.
输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
输出: true

Problem-solving ideas

"Prove safety offer" fourth title of the original title, in two ways:

  • With the present problem characteristic matrix, start looking from the top right matrix, each row exclusion / a.
  • Progressive half.

Reference Code

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

Expand the solution

//两种思路
//一种是:
//把每一行看成有序递增的数组,
//利用二分查找,
//通过遍历每一行得到答案,
//时间复杂度是nlogn
public class Solution {
    public boolean Find(int [][] array,int target) {
         
        for(int i=0;i<array.length;i++){
            int low=0;
            int high=array[i].length-1;
            while(low<=high){
                int mid=(low+high)/2;
                if(target>array[i][mid])
                    low=mid+1;
                else if(target<array[i][mid])
                    high=mid-1;
                else
                    return true;
            }
        }
        return false;
 
    }
}
 
//另外一种思路是:
//利用二维数组由上到下,由左到右递增的规律,
//那么选取右上角或者左下角的元素a[row][col]与target进行比较,
//当target小于元素a[row][col]时,那么target必定在元素a所在行的左边,
//即col--;
//当target大于元素a[row][col]时,那么target必定在元素a所在列的下边,
//即row++;
public class Solution {
    public boolean Find(int [][] array,int target) {
        int row=0;
        int col=array[0].length-1;
        while(row<=array.length-1&&col>=0){
            if(target==array[row][col])
                return true;
            else if(target>array[row][col])
                row++;
            else
                col--;
        }
        return false;
 
    }
}
Published 415 original articles · won praise 603 · Views 150,000 +

Guess you like

Origin blog.csdn.net/ft_sunshine/article/details/104064261