Google Interview

Possible duplicate:
Given an array of 2d, sorted in ascending order from left to right and top to bottom, the best way to find the target number?

In an interview with Google, the following was asked:

You are provided with a 2D array storing integers sorted vertically and horizontally.

Write a method that takes an integer as its value and prints a boolsaying whether the integer is in an array.

What is the best way to do this? And what is its temporal complexity?

+5
source share
3 answers

I would like to start with details on what it means to “sort vertically and horizontally”

, , , , , . O (log C + log R), C R, , . , O (log (C * R)), O (log N), N - . , 1D .

, :

1 2 3 4 5 6 7 8  9
2 3 4 5 6 7 8 9  10
3 4 5 6 7 8 9 10 11

:

  • . , . , :
  • . , . , ;
  • , , , , , ;

.

+5

, :

:

  • :
  • : .
  • : Return
  • , : Return Fail

: ( Martinho Fernandes)

O (N + M). , , N M .

:

--------------
| 1 | 4 | 6  | 
--------------
| 2 | 5 | 9  |
--------------
| *3* | 8 | 10 |
--------------

: 4

1: , 3 ( ).

3 < 4:


| 1 | 4 | 6  | 
--------------
| 2 | 5 | 9  |
--------------
| 3 | *8* | 10 |
--------------

2: 8 > 4: >


| 1 | 4 | 6  | 
--------------
| 2 | *5* | 9  |
--------------
| 3 | 8 | 10 |
--------------

3: 5 > 4:


| 1 | *4* | 6  | 
--------------
| 2 | 5 | 9  |
--------------
| 3 | 8 | 10 |
--------------

4:

4 = 4:

+18

, , - , , , . O(log NM), N M - .

: . , , , , , , , , , , .

0

All Articles