Find a special number in an array

后端 未结 9 1639
天命终不由人
天命终不由人 2020-12-25 09:07

There are many numbers in an array and each number appears three times excepting for one special number appearing once. Here is the question: how can I find the special numb

相关标签:
9条回答
  • 2020-12-25 09:52

    Following is another O(n) time complexity and O(1) extra space method

    suggested by aj. We can sum the bits in same positions for all the numbers and take modulo with 3.

    The bits for which sum is not multiple of 3, are the bits of number with single occurrence. Let us consider

    the example array {5, 5, 5, 8}.

    The 101, 101, 101, 1000

    Sum of first bits%3 = (1 + 1 + 1 + 0)%3 = 0;

    Sum of second bits%3 = (0 + 0 + 0 + 0)%0 = 0;

    Sum of third bits%3 = (1 + 1 + 1 + 0)%3 = 0;

    Sum of fourth bits%3 = (1)%3 = 1;

    Hence number which appears once is 1000

    #include <stdio.h>
    #define INT_SIZE 32
    
    int getSingle(int arr[], int n)
    {
    // Initialize result
    int result = 0;
    
    int x, sum;
    
    // Iterate through every bit
    for (int i = 0; i < INT_SIZE; i++)
    {
      // Find sum of set bits at ith position in all
      // array elements
      sum = 0;
      x = (1 << i);
      for (int j=0; j< n; j++ )
      {
          if (arr[j] & x)
            sum++;
      }
    
      // The bits with sum not multiple of 3, are the
      // bits of element with single occurrence.
      if (sum % 3)
        result |= x;
    }
    
    return result;
    }
    
    // Driver program to test above function
    int main()
    {
    int arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("The element with single occurrence is %d ",getSingle(arr, n));
    return 0;
    }
    
    0 讨论(0)
  • 2020-12-25 09:58

    Since nobody's saying it, I will: hashtable.

    You can calculate how many times each element occurs in the array in O(n) with simple hashtable (or hashmap).

    0 讨论(0)
  • 2020-12-25 10:00

    A possible algorithm (very generic, not tested) :

    function findMagicNumber(arr[0...n])
       magic_n := NaN
    
       if n = 1 then
          magic_n := arr[0]
       else if n > 1 then
          quicksort(arr)
    
          old_n := arr[0]
          repeat := 0
    
          for i := 1 to n
             cur_n := arr[i]
             repeat := repeat + 1
             if cur_n ≠ old_n then
                if repeat = 1 then
                   magic_n := old_n
                old_n := cur_n
                repeat := 0
    
       return magic_n
    
    0 讨论(0)
提交回复
热议问题