Finding first non-repeating number in integer array

后端 未结 4 1754
天涯浪人
天涯浪人 2021-02-20 03:55

I got this question for an exam:

Given an integer array find the first number which is not repeating in array using O(N) time complexity and O(1) space co

4条回答
  •  旧巷少年郎
    2021-02-20 04:30

    If there are exactly TWO (or in multiples of 2) entries for all elements except one element, which will be non-repeating, you can use XOR operator.

    Example:

    int x=arr[0];
    for(i=1;i<1000;i++)
      x^=a[i];
    printf("Non-repeating: %d",x);
    

    Any number XORed with itself is 0. So, if any number appears twice it will be 0 in the overall XOR result, thus leaving only the non-repeating number in x.

    Note: If you have 1 million numbers, the variable to store the XOR result must be large enough.

提交回复
热议问题