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?
考虑使用位运算
-那数组分为两组,每个组只有一个出现一次的数字,单独进行异或处理,考虑用全部异或的方式
public class Solution {
public int[] singleNumber(int[] nums) {
int xOne = 0;
for (int x : nums) {
xOne ^= x;
}
// 获取第一个位1的索引
int k = 0;
for (k = 0; k < Integer.SIZE; ++ k) {
if (((xOne >>> k) & 1) == 1) {
break;
}
}
int xTwo = 0;
for (int x : nums) {
if (((x >>> k) & 1) == 1) {
xTwo ^= x;
}
}
return new int[] {xTwo, xOne ^ xTwo};
}
}
更多的leetcode的经典算法,查看我的leetcode专栏
2025 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123