C ++ solution to a problem to prove safety Offer_

1. Find a 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.
 
C++55
 
Idea, originally thought to write it again violence, but violence is estimated the interview directly pass, so the thinking has been optimized, the first can determine the size of the two-dimensional array is a rectangle, that is, the length of each are equal to one-dimensional two-dimensional array. Then try to determine where the line answers, and then determine the column where the answers. But this is wrong thinking . Because the cause of the error, respectively, subject only to ensure the longitudinal and transverse incremental increase, it does not guarantee the same time horizontal and vertical increments, it is not possible to determine the row and column, respectively. Then looked at the idea of the forum is very clear,
/ * Ideas
* Matrix is ​​ordered, the lower left corner from the point of view, up diminishing numbers, the right numbers increase,
* Therefore, from the lower left corner to start looking when you want to find digital numbers larger than the lower-left corner. Right
* To find a figure than the lower left corner of the digital hours, move up
*/

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

    }
};
 
  
The above is my code, write a thousand times a runtime error RE in the debugging process, ultimately handwriting test sample.
int main()
{
    vector<int>vp;
    vector<vector<int> >v;
    for(int i=0;i<5;i++){
        vp.push_back(i);
    }
    v.push_back(vp);
    vp.clear();
    for(int i=0;i<5;i++){
        vp.push_back(i+5);
    }

    v.push_back(vp);
    vp.clear();
    for(int i=0;i<5;i++){
        vp.push_back(i+10);
    }
    v.push_back(vp);


    Solution s;
    bool flag = s.Find(11,v);
    if(flag){
        cout<<"yes"<<endl;
    }else{
        cout<<"NO"<<endl;

    }

    return 0;
}

 

These are the test sample code, and finally found the test data in the presence of null data. Therefore 

IF (array.size () == 0) {return to false;}
IF (Array [0] .size () == 0) {return to false;}

need to add two words, consider the special circumstances.


 

Guess you like

Origin www.cnblogs.com/Flydoggie/p/11864430.html