1. class Solution {
  2. public int[] singleNumbers(int[] nums) {
  3. int res=0;
  4. int tmp=1;
  5. int a=0;
  6. int b=0;
  7. for(int i:nums){
  8. res^=i;
  9. }
  10. while((tmp&res)==0){
  11. tmp<<=1;
  12. }
  13. // 按照某位进行&运算
  14. for(int i:nums){
  15. if((tmp&i)==0){
  16. a^=i;
  17. }else{
  18. b^=i;
  19. }
  20. }
  21. return new int[]{a,b};
  22. }//借鉴 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/
  23. }

剑指 Offer 56 - I. 数组中数字出现的次数

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

示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]

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

限制:

  • 2 <= nums.length <= 10000