Search a 2D Matrix

Source: Internet
Author: User

is basically binary search, I have a good grasp of the

Determine the row first, and then determine the column

1      Public BooleanSearchmatrix (int[] Matrix,inttarget) {2         if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0) {3             return false;4         }5         intLow = 0;6         intHigh = Matrix.length-1;7          while(Low <=High ) {8             intMid = low+ (high-low)/2;9             if(Matrix[mid][0] >target) {TenHigh = Mid-1; One}Else if(Matrix[mid][0] <target) { ALow = Mid+1; -}Else { -                 return true; the             } -         } -         if(High < 0) { -             return false; +         } -         intL = 0; +         intr = Matrix[0].length-1; A          while(L <=r) { at             intMID = L + (r-l)/2; -             if(Matrix[high][mid] <target) { -L = mid+1; -}Else if(Matrix[high][mid] >target) { -r = Mid-1; -}Else { in                 return true; -             } to         } +         return false; -}

Bug Record:

1.high = Length-1. Don't forget to lose one, I forgot it two times.

2. When it is smaller than the matrix smallest inside, pay attention to judgment, that is, 17-19 lines

Search a 2D Matrix

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.