Search a 2D Matrix II Java Solutions

Source: Internet
Author: User

Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:

    • Integers in each row is sorted in ascending from left to right.
    • Integers in each column is sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[  [1,   4,  7, one, a],  [2,   5, 8,, +  ],  [3,   6,  9, +, +],  [10, 13, 14, 17,  [18, 21, 23, 26, 30]

Given target = 5 , return true .

Given target = 20 , return false .

1  Public classSolution {2      Public BooleanSearchmatrix (int[] Matrix,inttarget) {3         if(Matrix.length = = 0 | | matrix[0].length = = 0)return false;4         inti = 0,j = Matrix[0].length-1;5          while(I < matrix.length && J >= 0){6             if(Matrix[i][j] = = target)return true;7             if(Matrix[i][j] < target) i++;8             Elsej--;9         }Ten         return false; One     } A}

The matrix is special and can be compared from the top right x, if target > x, then to the next line, if Target < X, then go back one column. The topic has appeared in the beauty of programming.

Solution 2: The problem can also be found using the dichotomy method.

Search a 2D Matrix II Java Solutions

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.