Nếu O (1) không gian hạn chế đã không có, bạn có thể đã đi cho một hashmap với các giá trị là số lần xuất hiện.
int getUniqueElement(int[] arr)
{
int ones = 0 ; //At any point of time, this variable holds XOR of all the elements which have appeared "only" once.
int twos = 0 ; //At any point of time, this variable holds XOR of all the elements which have appeared "only" twice.
int not_threes ;
for(int x : arr)
{
twos |= ones & x ; //add it to twos if it exists in ones
ones ^= x ; //if it exists in ones, remove it, otherwise, add it
// Next 3 lines of code just converts the common 1's between "ones" and "twos" to zero.
not_threes = ~(ones & twos) ;//if x is in ones and twos, dont add it to Threes.
ones &= not_threes ;//remove x from ones
twos &= not_threes ;//remove x from twos
}
return ones;
}
Về cơ bản, nó sử dụng thực tế là x^x = 0
và 0^x=x
. Vì vậy, tất cả các yếu tố kết hợp có được XOR'd và biến mất rời khỏi yếu tố cô đơn.
Tóm tắt:
Nếu một chút đã có sẵn, hãy thêm nó vào cặp đôi.
XOR sẽ thêm bit này vào bit nếu không có hoặc xóa bit này khỏi bit nếu nó đã ở đó.
Nếu một bit nằm trong cả hai cái và cặp đôi, hãy xóa nó ra khỏi những cái và cặp đôi.
Khi hoàn tất, các thẻ đó chứa các bit chỉ xuất hiện 3 * n + 1 lần, là các bit cho phần tử chỉ xuất hiện một lần.
Gợi ý: sum họ ... – wildplasser