题目描述

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/

示例

  1. 输入:nums = [1,2,10,4,1,4,3,3]
  2. 输出:[2,10] 或 [10,2]

解题思路

题目详解:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solution/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-by-leetcode/
主要思想是分组异或:如果我们可以把所有数字分成两组,使得:

  1. 两个只出现一次的数字在不同的组中;
  2. 相同的数字会被分到相同的组中。

那么我们对这两组在分别进行异或即可以得到对应的数字

  1. class Solution {
  2. public:
  3. vector<int> singleNumbers(vector<int>& nums) {
  4. int ret = 0;
  5. for (int n : nums)
  6. ret ^= n;
  7. int div = 1;
  8. while ((div & ret) == 0)
  9. div <<= 1;
  10. int a = 0, b = 0;
  11. for (int n : nums)
  12. if (div & n)
  13. a ^= n;
  14. else
  15. b ^= n;
  16. return vector<int>{a, b};
  17. }
  18. };