27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 9 | Sorting <strong>and</strong> Searching<br />

9.6 Given a matrix in which each row <strong>and</strong> each column is sorted, write a method to find<br />

an element in it.<br />

SOLUTION<br />

Assumptions:<br />

pg 66<br />

»»<br />

Rows are sorted left to right in ascending order. Columns are sorted top to bottom in<br />

ascending order.<br />

»»<br />

Matrix is of size MxN.<br />

This algorithm works by elimination. Every move to <strong>the</strong> left (--col) eliminates all <strong>the</strong> elements<br />

below <strong>the</strong> current cell in that column. Likewise, every move down eliminates all <strong>the</strong> elements<br />

to <strong>the</strong> left of <strong>the</strong> cell in that row.<br />

1 boolean FindElem(int[][] mat, int elem, int M, int N) {<br />

2 int row = 0;<br />

3 int col = N-1;<br />

4 while (row < M && col >= 0) {<br />

5 if (mat[row][col] == elem) {<br />

6 return true;<br />

7 } else if (mat[row][col] > elem) {<br />

8 col--;<br />

9 } else {<br />

10 row++;<br />

11 }<br />

12 }<br />

13 return false;<br />

14 }<br />

CareerCup.com<br />

1 8 4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!