How can I find a number which occurs an odd number of times in a SORTED array in O(n) time?

后端 未结 15 2017
梦如初夏
梦如初夏 2021-01-30 10:31

I have a question and I tried to think over it again and again... but got nothing so posting the question here. Maybe I could get some view-point of others, to try and make it w

15条回答
  •  清酒与你
    2021-01-30 11:27

    Assume indexing start at 0. Binary search for the smallest even i such that x[i] != x[i+1]; your answer is x[i].

    edit: due to public demand, here is the code

    int f(int *x, int min, int max) {
      int size = max;
      min /= 2;
      max /= 2;
      while (min < max) {
        int i = (min + max)/2;
        if (i==0 || x[2*i-1] == x[2*i])
          min = i+1;
        else
          max = i-1;
      }
      if (2*max == size || x[2*max] != x[2*max+1])
        return x[2*max];
      return x[2*min];
    }
    

提交回复
热议问题