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

后端 未结 20 744
暖寄归人
暖寄归人 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:29

    If O(M log(N)) solution is ok for an MxN array -

    template 
    struct MN * get(int a[][n], int k, int M, int N){
      struct MN *result = new MN;
      result->m = -1;
      result->n = -1;
    
      /* Do a binary search on each row since rows (and columns too) are sorted. */
      for(int i = 0; i < M; i++){
        int lo = 0; int hi = N - 1;
        while(lo <= hi){
          int mid = lo + (hi-lo)/2;
          if(k < a[i][mid]) hi = mid - 1;
          else if (k > a[i][mid]) lo = mid + 1;
          else{
            result->m = i;
            result->n = mid;
            return result;
          }
        }
      }
      return result;
    }
    

    Working C++ demo.

    Please do let me know if this wouldn't work or if there is a bug it it.

提交回复
热议问题