Finding repeating signed integers with O(n) in time and O(1) in space

后端 未结 7 474
慢半拍i
慢半拍i 2021-02-04 08:49

(This is a generalization of: Finding duplicates in O(n) time and O(1) space)

Problem: Write a C++ or C function with time and space complexities of O(n) and O(1) respec

相关标签:
7条回答
  • 2021-02-04 09:31

    I really don't see how you can have only O(1) space and not modify the initial array. My guess is that you need an additional data structure. For example, what is the range of the integers? If it's 0..N like in the other question you linked, you can have an additinal count array of size N. Then in O(N) traverse the original array and increment the counter at the position of the current element. Then traverse the other array and print the numbers with count >= 2. Something like:

    int* counts = new int[N];
    for(int i = 0; i < N; i++) {
        counts[input[i]]++;
    }
    
    for(int i = 0; i < N; i++) {
        if(counts[i] >= 2) cout << i << " ";
    }
    
    delete [] counts;
    
    0 讨论(0)
提交回复
热议问题