website/content/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.给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。
注意:
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
}