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?
题目要求是给定一个整形数组,该数组中只有一个元素不是成对出现的,找到这个元素。要求算法的时间复杂度是线性的。
这道题的解题思路就是:一个整数和他自己异或得到的结果是零。
所以该题的解法就是初始化一个值为0的数,与该数组中每一个数执行异或操作,最后得到的数便是该数组中唯一一个不成对的整数。
下面是用java实现的代码:
public class Solution {
public int singleNumber(int[] A) {
int result = 0;
for(int i = 0;i<A.length;i++){
result = result ^ A[i];
}
return result;
}
}
当然此题如果不考虑时间复杂度,做法还是很多的,比如用哈希表来完成。
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < A.length; i++){
if(!map.containsKey(A[i])) {
map.put(A[i], i);
}
else {
map.remove(A[i]);
}
}
for (int i = 0; i < A.length; i++){
if(map.containsKey(A[i])) {return A[i];}
}
return 0;