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

后端 未结 7 676
慢半拍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:14

    Say you can use the fact you are not using all the space you have. You only need one more bit per possible value and you have lots of unused bit in your 32-bit int values.

    This has serious limitations, but works in this case. Numbers have to be between -n/2 and n/2 and if they repeat m times, they will be printed m/2 times.

    void print_repeats(long a[], unsigned size) {
        long i, val, pos, topbit = 1 << 31, mask = ~topbit;
        for (i = 0; i < size; i++)
            a[i] &= mask;
    
        for (i = 0; i < size; i++) {
            val = a[i] & mask;
            if (val <= mask/2) {
               pos = val;
            } else {
                val += topbit;
                pos = size + val;
            }
            if (a[pos] < 0) {
                printf("%d\n", val);
                a[pos] &= mask;
            } else {
                a[pos] |= topbit;
            }
        }
    }
    
    void main() {
        long a[] = {1, 0, -2, 4, 4, 1, 3, 1, -2};
        print_repeats(a, sizeof (a) / sizeof (long));
    }
    

    prints

    4
    1
    -2
    

提交回复
热议问题