Find three numbers appeared only once

后端 未结 6 1977
说谎
说谎 2020-12-08 03:15

In a sequence of length n, where n=2k+3, that is there are k unique numbers appeared twice and three numbers appeared only once.

The question is: how to fin

6条回答
  •  情歌与酒
    2020-12-08 04:06

    The problem gets harder and harder as you add more unique values, mainly because you can choose A,B,C such that A xor B xor C = 0. It gets harder and harder to detect if a subset of the values has the same checksum because it contains all the unique values, or because it omitted values which happened to xor to 0.

    You can do 3 values in constant space and O(n*k) time, where k is the number of bits in the largest integer. (So O(n) time for your typical case: 32-bit integers.)

    It would be interesting to find out if the time bound becomes non-linear in N as the number of unique values increases and you continue to require constant space.

    //Special check for 0, because otherwise we don't know A xor B xor C != A xor B
    if items unique-contains 0 then
        return 0 ++ SubProblem2Unique(items - 0)
    //Compute A xor B xor C
    val x = fold xor items
    //Try to find a split which separates A and B from C.
    for i in 0..WORD_SIZE
        //see if the checksum splits
        val x1 = fold xor [e in items where e & (1<

提交回复
热议问题