题目描述:
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?
解答
方法一:采用XOR(异或)方式解答。异或的基本知识大家可以自行查询。在此举例如2^2=0,2^1=3,2^0=2。其先转为二进制按位异或后转为10进制表示。故对于一个数列1 2 2 3 3,使用异或可得 1^2^2^3^3 = 1
public class Solution {
public int singleNumber(int[] A) {
int result = A[0];
for(int i=1;i<A.length;i++){
result = result^A[i];
}
return result;
}
}
/**
* 方法名称:singleNumber()
* 方法描述:采用排序方式解答
* @param
* @return String
* @Exception
*/
public int singleNumberSort(int[] A){
if(A.length == 1){
return A[0];
}
//按照升序排列
Arrays.sort(A);
//排序之后,相同的数字成对存在 如 1,2,2,3,3;2,2,3,4,4;故此设定递增步长为2
for(int i=0;i<A.length-1;i+=2){
if(A[i] != A[i+1]){
return A[i];
}
}
return A[A.length-1];
}
public int singleNumber(int[] A) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<A.length;i++){
int value = 0;
if(map.containsKey(A[i])){
map.remove(A[i]);
}else{
map.put(A[i], value+1);
}
}
return map.entrySet().iterator().next().getKey();
}