您的位置:首页 > 其它

260. Single Number III

2018-02-13 21:47 197 查看
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?
分析:
首先得出nums数组的所有异或和val,找到val中bit不为1的位的位置x处,将nums中对应x处为1的nums[i]异或,将nums中对应x处为0的nums[i]异或,分别得出result[0]、result[1]。
程序如下所示:class Solution {
public int[] singleNumber(int[] nums) {
int[] result = new int[2];
int val = 0, len = nums.length;
for (int i = 0; i < len; ++ i){
val = val^nums[i];
}
while (val != 0){
if ((val&(val - 1)) == 0){
break;
}
val = val&(val - 1);
}
for (int i = 0; i < len; ++ i){
if ((nums[i]&val) != 0){
result[0] = result[0]^nums[i];
}
else {
result[1] = result[1]^nums[i];
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: