Algorithm Note _130: Lookup of row and column increment matrices (Java)

Source: Internet
Author: User

Directory

1 Problem Description

2 Solutions

2.1 Positioning Method

  1 problem description

in a two-dimensional array of M row n columns, each row is arranged in ascending order from left to right, and each column is arranged in ascending order from top to bottom. Now that you have entered such a two-dimensional array and an integer, complete a function that determines whether the array contains the integer.

2 Solutions 2.1 Positioning method

the time complexity of the algorithm below is O (M + N), space complexity is O (1).

The specific code is as follows:

Package Com.liuzhen.practice; Public classMain { PublicBoolean Youngmatrix (int[] A,intkey) {        inti =0, j = a[0].length-1; inttemp =A[i][j];  while(true) {            if(temp = =key) {                return true; } Else if(Temp < key && I < a.length-1) {Temp= a[++i]            [j]; } Else if(Temp > key && J >0) {Temp= a[i][--J]; } Else {                return false; }        }    }         Public Static voidMain (string[] args) {main test=NewMain (); int[] A = {{1,2,8,9},{2,4,9, A},{4,7,Ten, -},{6,8, One, the}}; if(Test. Youngmatrix (A,6) ) System. out. println ("The matrix A contains element 6"); ElseSystem. out. println ("element 6 is not included in matrix a"); if(Test. Youngmatrix (A,5) ) System. out. println ("The matrix A contains element 5"); ElseSystem. out. println ("element 5 is not included in matrix a"); }}

Operation Result:

Matrix A contains element 6 matrix A does not contain element 5

Resources:

1."Programming method interview and algorithmic experience" July

Algorithm Note _130: Lookup of row and column increment matrices (Java)

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.