Point of Offer: finding in a two-dimensional array

Source: Internet
Author: User

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
    1. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.