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].
public class Solution {
public int[] singleNumber(int[] nums) {
int a = 0;
int b = 0;
for (int i : nums) {
a ^= i;
}
int rightOne = a & (~a + 1);
for (int i : nums) {
if ((rightOne & i) != 0) {
b ^= i;
}
}
return new int[]{b, a^b};
}
}
本文介绍了一种高效的算法,用于从一个整数数组中找出仅出现一次的两个元素,其余元素均出现两次。通过使用异或运算和位操作实现,该算法能在O(n)时间内解决问题。
2万+

被折叠的 条评论
为什么被折叠?



