您的位置:首页 > 其它

LeetCode--136. Single Number

2016-04-18 15:49 375 查看
题目:Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

一开始自己写了个可以AC的

public class Solution {
public int singleNumber(int[] nums) {
HashSet<Integer> set=new HashSet<Integer>();

for(int i=0;i<nums.length;i++){
if(!set.contains(nums[i]))
set.add(nums[i]);
else
set.remove(nums[i]);
}
Iterator iterator=set.iterator();
return (Integer)iterator.next();

}
}
不过后来觉得太没技巧了,肯定不是比较好的答案。上网请教别人,果然是有技巧的,所以写下来记录一下

o(n)的算法只能是线性扫描一遍,可能的相法是位运算。对于异或来说:

1. 异或运算是可交换,即 a ^ b = b ^ a

2. 0 ^ a = a

那么如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....,可以将所有相同元素交换至相邻位置,首先运算

素,则会产生(n - 1)/2个0异或积,剩余一个单一元素,他们的异或积为这个单一元素自己,得解。


public class Solution {
public int singleNumber(int[] nums) {
int ans=0;

for(int i=0;i<nums.length;i++){
ans=ans^nums[i];
}
return ans;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: