website/content.en/ChapterFour/0200~0299/0260.Single-Number-III.md
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Example:
Input: [1,2,1,3,2,5]
Output: [3,5]
Note:
[5, 3] is also correct.Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Note:
package leetcode
func singleNumberIII(nums []int) []int {
diff := 0
for _, num := range nums {
diff ^= num
}
// Get its last set bit (lsb)
diff &= -diff
res := []int{0, 0} // this array stores the two numbers we will return
for _, num := range nums {
if (num & diff) == 0 { // the bit is not set
res[0] ^= num
} else { // the bit is set
res[1] ^= num
}
}
return res
}