How does one remove duplicate elements in place in an array in O(n) in C or C++?

后端 未结 7 1727
长情又很酷
长情又很酷 2020-12-16 21:43

Is there any method to remove the duplicate elements in an array in place in C/C++ in O(n)? Suppose elements are a[5]={1,2,2,3,4} then resulting array should c

相关标签:
7条回答
  • 2020-12-16 22:44

    Yes. Because access (insertion or lookup) on a hashtable is O(1), you can remove duplicates in O(N).

    Pseudocode:

    hashtable h = {}
    numdups = 0
    for (i = 0; i < input.length; i++) {
        if (!h.contains(input[i])) {
            input[i-numdups] = input[i]
            h.add(input[i])
        } else {
            numdups = numdups + 1
        }
    

    This is O(N).

    Some commenters have pointed out that whether a hashtable is O(1) depends on a number of things. But in the real world, with a good hash, you can expect constant-time performance. And it is possible to engineer a hash that is O(1) to satisfy the theoreticians.

    0 讨论(0)
提交回复
热议问题