20140920 search for a two-dimensional matrix of Baidu pen questions

Source: Internet
Author: User

Question:

There is such a two-dimensional matrix A [n] [N], satisfying j <k, 1) A [I] [J] <A [I] [k]; 2) A [J] [I] <A [k] [I] (in fact, the data is decreased from the upper left corner to the lower right corner), given a number target, how to quickly search whether the two-dimensional coordinates are output in the matrix; otherwise, null is output. (assume that the data is not repeated)
For example
12  34  56  78  90  96
13  35  57  79  91  97
14  36  58  80  93  98
15  37  59  81  94  99
16  38  60  82  95  120
17  39  61  83  100  123
Search for 60 and output <4, 2>

Practice: traverse the matrix from the lower left corner, that is, make I = n-1, j = 0. If the value of (I, j) is greater than the search value, then I --, if it is small, J ++ is found. If it is equal, it is found.

Code:

void find(int array[][6], int n, int target){        int i = n - 1, j = 0;        while(i >= 0 && j < n)        {                if(array[i][j] == target)                {                        cout << '(' << i << ',' << j << ')' << endl;                        return;                }                else if(array[i][j] > target)                        i--;                else j++;        }                cout << "NULL\n";}
Result:

12
(0, 0)
34
(0, 1)
56
(0, 2)
78
(0, 3)
99
(3, 5)
123
(5, 5)
11
Null


20140920 search for a two-dimensional matrix of Baidu pen questions

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.