Limit input data to achieve a better Big O complexity

前端 未结 3 1964
傲寒
傲寒 2020-12-22 14:40

You are given an unsorted array of n integers, and you would like to find if there are any duplicates in the array (i.e. any integer appearing more than once). D

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 14:54

    A variance of Bucket Sort will do. This will give you complexity of O(n) where 'n' is the number of input elements.

    But one restriction - max value. You should know the max value your integer array can take. Lets say it as m.

    The idea is to create a bool array of size m (all initialized to false). Then iterate over your array. As you find an element, set bucket[m] to true. If it is already true then you've encountered a duplicate.

    A java code,

    
    
    // alternatively, you can iterate over the array to find the maxVal which again is O(n).
    public boolean findDup(int [] arr, int maxVal)
    {
            // java by default assigns false to all the values.
        boolean bucket[] = new boolean[maxVal];
    
        for (int elem : arr)
        {
    
            if (bucket[elem])
            {
               return true; // a duplicate found
            }
    
            bucket[elem] = true;
        }   
        return false;   
    }
    
    

    But the constraint here is the space. You need O(maxVal) space.

提交回复
热议问题