How do I search for a number in a 2d array sorted left to right and top to bottom?

后端 未结 20 721
暖寄归人
暖寄归人 2020-11-22 13:03

I was recently given this interview question and I\'m curious what a good solution to it would be.

Say I\'m given a 2d array where all the numbers i

20条回答
  •  清酒与你
    2020-11-22 13:18

    Interesting question. Consider this idea - create one boundary where all the numbers are greater than your target and another where all the numbers are less than your target. If anything is left in between the two, that's your target.

    If I'm looking for 3 in your example, I read across the first row until I hit 4, then look for the smallest adjacent number (including diagonals) greater than 3:

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

    Now I do the same for those numbers less than 3:

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

    Now I ask, is anything inside the two boundaries? If yes, it must be 3. If no, then there is no 3. Sort of indirect since I don't actually find the number, I just deduce that it must be there. This has the added bonus of counting ALL the 3's.

    I tried this on some examples and it seems to work OK.

提交回复
热议问题