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

后端 未结 15 2019
梦如初夏
梦如初夏 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:21

    Try this:

    int getOddOccurrence(int ar[], int ar_size)
    {
         int i;
         int xor = 0; 
         for (i=0; i < ar_size; i++)     
            xor = xor ^ ar[i];
    
         return res;
    }
    

    XOR will cancel out everytime you XOR with the same number so 1^1=0 but 1^1^1=1 so every pair should cancel out leaving the odd number out.

提交回复
热议问题