您的位置:首页 > 其它

【Leetcode】Single Number

2015-11-30 22:05 267 查看
题目链接:https://leetcode.com/problems/single-number/

题目:

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?

思路:

1、用HashMap,时间复杂度O(n),空间复杂度O(n)

2、用位操作,考虑异或的特点:x^x=0,异或满足结合律和交换律,0^x=x。

对数组所有元素异或一次,即n[0]^n[1]^n[2].....运用交换律和结合律可以把相同元素放一起异或结果为0,而0和剩余元素异或不会改变结果,所以

最后得到结果 为出现次数为奇数的元素。空间复杂度为O(1)。

算法1:

public int singleNumber(int[] nums) {
Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
for (int i : nums) {
if (maps.containsKey(i)) {
maps.remove(i);
} else {
maps.put(i, 1);
}
}
return (int) maps.keySet().toArray()[0];
}


算法2:

public int singleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: