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?
Tag:Hash Table BitManipulation
public class Solution {
public int singleNumber(int[] A) {
}
}
分析:
给你一个整形数组,除了一个元素只出现一次外,每个元素都出现两次,请找到出现2次的那个数。
注意:算法需要在线性时间复杂度内完成。
方法:
1,使用哈希表,如果不存在该整数,保存,如果存在,移除。最后剩下的那个key
就是最后的结果。
import java.util.Enumeration;
import java.util.Hashtable;
public class Solution {
public int singleNumber(int[] A) {
Hashtable<Integer, Integer> numbers = new Hashtable<Integer, Integer>();
for (int i = 0; i < A.length; i++) {
if (numbers.containsKey(A[i]))
numbers.remove(A[i]);
else
numbers.put(A[i], A[i]);
}
Enumeration<Integer> single = numbers.keys();
return single.nextElement();
}
}
2,异或
方法来自leetcode上的discuss.
因为A异或A 得到0. 而最后就剩下0异或那个数字。得到最后结果。
因为异或满足交换律。所以顺序没关系。