描述
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.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example, [5, 3] is also correct.
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
分析
这道题和leetcode-136-Single-Number不同的是,这里面有两个单身狗,仍然是位操作,如果能将两个单身狗分开,也就是说将所有元素分成两组,两组都是leetcode-136-Single-Number的情况,思路就简单了,怎么做呢?假设两个单身狗是a,b,将所有元素异或的结果即a,b异或的结果,这里记为c,通过c & ~(c-1)
可以求得从左到右的第一个1,这个1怎么得到的?通过a,b异或得到的,自然可以通过这一位将a,b分开。
解决方案1(C++)
1 | class Solution { |