[Wins the offer] - Find two-dimensional array

Title Description

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Problem-solving ideas:

First, select the numbers in the upper right corner of the array,

[1] If this number is equal to the check number, the search ends;

[2] If the number is greater than the number to look for, then remove the column number is located, such as (A);

[3] If the number is less than the number you are looking for, then remove the row number is located, such as (c)

Code is implemented as follows:

 

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

 

Guess you like

Origin blog.csdn.net/yuemingyang7010/article/details/91950338