[Algorithm] to find the number of matrices in which the rows and columns are well sequenced

Source: Internet
Author: User

Title:

Given a n*m matrix and an integer k,matrix, each row and each column is well-ordered. Implement a function to determine if k is in the matrix.

For example:

0 1 2 5

2 3 4 7

4 4 4 8

5 7 7 9

Returns True if K is 7, or False if K is 6.

Requires a time complexity of O (n+m) with an O (1) Additional space complexity.

Ideas:

1. Start looking for (row=0,col=m-1) from the number of the top right corner of the matrix.

2. Compare the current number of matrix[row][col] with the K relationship:

    • If it is equal to K, the description has been found, direct but true.
    • If larger than K, because each column of the matrix is already ordered, so in the current number of columns, the number below the current number will be larger than K, then there is no need to continue to look in the Col column, so col--, repeat step 2.
    • If it is smaller than k, because each row of the matrix is already ordered, so in the current number of rows, the number of the left of the current number will be larger than K, then there is no need to continue to find on row row, so row++, repeat step 2.

3. Returns False if no number is found that is equal to K if found out of bounds.

 Public Static BooleanIscontains (int[] Matrix,intK) {intRow = 0; intCol = matrix[0].length-1;  while(Row < matrix.length && col >-1) {            if(Matrix[row][col] = =K) {return true; } Else if(Matrix[row][col] >K) {col--; } Else{row++; }        }        return false; }

[Algorithm] to find the number of matrices in which the rows and columns are well sequenced

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.