class Solution {
public int[] singleNumbers(int[] nums) {
int res=0;
int tmp=1;
int a=0;
int b=0;
for(int i:nums){
res^=i;
}
while((tmp&res)==0){
tmp<<=1;
}
// 按照某位进行&运算
for(int i:nums){
if((tmp&i)==0){
a^=i;
}else{
b^=i;
}
}
return new int[]{a,b};
}//借鉴 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/
}
剑指 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