Limit input data to achieve a better Big O complexity

前端 未结 3 1941
傲寒
傲寒 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条回答
  •  感情败类
    2020-12-22 15:17

    nested loops get you O(N*M) or O(N*log(M)) for O(N) you can not use nested loops !!!

    I would do it by use of histogram instead:

    DWORD in[N]={ ... }; // input data ... values are from < 0 , M )
    DWORD his[M]={ ... }; // histogram of in[]
    int i,j;
    
    // compute histogram O(N)
    for (i=0;i

    [Notes]

    • if value range is too big with sparse areas then you need to convert his[]
    • to dynamic list with two values per item
    • one is the value from in[] and the second is its occurrence count
    • but then you need nested loop -> O(N*M)
    • or with binary search -> O(N*log(M))

提交回复
热议问题