More elegant way to check for duplicates in C++ array?

后端 未结 12 1406
梦如初夏
梦如初夏 2020-12-01 09:36

I wrote this code in C++ as part of a uni task where I need to ensure that there are no duplicates within an array:

// Check for duplicate numbers in user in         


        
12条回答
  •  粉色の甜心
    2020-12-01 10:07

    I'm not sure why this hasn't been suggested but here is a way in base 10 to find duplicates in O(n).. The problem I see with the already suggested O(n) solution is that it requires that the digits be sorted first.. This method is O(n) and does not require the set to be sorted. The cool thing is that checking if a specific digit has duplicates is O(1). I know this thread is probably dead but maybe it will help somebody! :)

    /*
    ============================
    Foo
    ============================
    * 
       Takes in a read only unsigned int. A table is created to store counters 
       for each digit. If any digit's counter is flipped higher than 1, function
       returns. For example, with 48778584:
        0   1   2   3   4   5   6   7   8   9
       [0] [0] [0] [0] [2] [1] [0] [2] [2] [0]
    
       When we iterate over this array, we find that 4 is duplicated and immediately
       return false.
    
    */
    bool Foo( unsigned const int &number)
    {
        int temp = number;
        int digitTable[10]={0};
    
        while(temp > 0)
        {
            digitTable[temp % 10]++; // Last digit's respective index.
            temp /= 10; // Move to next digit
        }
    
        for (int i=0; i < 10; i++)
        {
            if (digitTable [i] > 1)
            {
                return false;
            }
        }
        return true;
    }
    

提交回复
热议问题