Best case Big O complexity

前端 未结 2 1524
走了就别回头了
走了就别回头了 2021-01-29 11:54

The question:
how can you limit the input data to achieve a better Big O complexity? Describe an algorithm for handling this limited data to find if there are an

2条回答
  •  终归单人心
    2021-01-29 12:04

    You can achieve a better big O complexity if you know the max value your integer array can take. Lets say it as m. The algorithm to do it is the variance of Bucket Sort. The complexity is O(n). Source code of algorithm:

    public boolean HasDuplicates(int [] arr, int m)
    {
    
        boolean bucket[] = new boolean[m];
    
        for (int elem : arr)
        {
    
            if (bucket[elem])
            {
               return true; // a duplicate found
            }
    
            bucket[elem] = true;
        }   
        return false;   
    }
    

提交回复
热议问题