Sword Point Offer (book): Finding in a two-dimensional array

Source: Internet
Author: User

Title: In a two-dimensional array (each one-dimensional array has the same length), 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.

Analysis: Key points: Each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. From the key point we need to think about its rules: the right side is greater than the left, and the lower is greater than the above. Starting point: Four corner, upper left corner: the right below are incremented, that is, the search point is below the bottom of the possibility, is not feasible; upper left corner: down, to the left, that is, to find the point than the value of this corner, go down, smaller than the value of this point, go left, feasible, discard the upper corner. The lower-left corner is similar to this. The lower-right corner is similar to the upper-left corner. So, start with the top right or bottom left corner.

 Public classSolution04 {BooleanFindint[] Matrix,intNumber ) {        if(Matrix = =NULL|| Matrix.length <= 0 | | Matrix[0].length <= 0) {            return false; }        introw = Matrix.length-1; intCol = 0;  while(Row >= 0 && Col < matrix[0].length) {if(matrix[row][col]==Number ) {                return true; }            if(matrix[row][col]<Number ) {Col++; }Else{row--; }        }        return false; }     Public Static voidMain (string[] args) {Solution04 solution03=NewSolution04 (); System.out.print (Solution03.find (New int[][]{{3, 2, 1},{6, 4, 5}}, 7)); }}

Sword Point Offer (book): Finding in a two-dimensional array

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.