Algorithm to find two repeated numbers in an array, without sorting

前端 未结 24 2174
南方客
南方客 2020-11-28 06:58

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.

E.g. in {2, 3, 6, 1, 5, 4

24条回答
  •  孤街浪徒
    2020-11-28 07:10

    There is a O(n) solution if you know what the possible domain of input is. For example if your input array contains numbers between 0 to 100, consider the following code.

    bool flags[100];
    for(int i = 0; i < 100; i++)
        flags[i] = false;
    
    for(int i = 0; i < input_size; i++)
        if(flags[input_array[i]])
             return input_array[i];
        else       
            flags[input_array[i]] = true;
    

    Of course there is the additional memory but this is the fastest.

提交回复
热议问题