Title Description
In a two-dimensional array, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, enter a two-dimensional array and an integer to determine if the array contains the integer.
Topic links
Thinking of solving problems
- Consider each row as an array of sequential increments, using
二分查找
, by iterating through each row to get answers, the time complexity is NLOGN
Public class solution {Public boolean Find(int [] [] array,int target) { for(intI=0; i<array.length;i++) {intlow=0;inthigh=array[i].length-1; while(Low<=high) {intMID = low + (high-low)/2;//int mid= (Low+high)/2; possible overflow if(Target>array[i][mid]) low=mid+1;Else if(Target<array[i][mid]) high=mid-1;Else return true; } }return false; } }
-
Note: Why not search from the upper left corner, because the upper left corner of the right and downward are incremented, then for a point, for the right and downward will produce a fork , is not conducive to coding; but if we choose to search from the bottom left, if it is greater than the right, if it is less than the downward.
Public class solution {Public boolean Find(int [] [] array,int target) {introw=0;intcol=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++;Elsecol--; }return false; } }
Point of Offer: finding in a two-dimensional array