image.pngimage.png

解题思路

位运算

diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。

  1. public int[] singleNumber(int[] nums) {
  2. int diff = 0;
  3. int[] res = new int[2];
  4. for (int num : nums)
  5. diff ^= num;
  6. diff &= -diff;
  7. for (int num : nums) {
  8. if ((num & diff) == 0)
  9. res[0] ^= num;
  10. else
  11. res[1] ^= num;
  12. }
  13. return res;
  14. }