描述
給出 2 * n + 1
個數字,除其中一個數字之外其他每個數字均出現兩次,找到這個數字。
樣例:
給出 [1,2,2,1,3,4,3],返回 4
利用HashMap的特性
public static int singleNumber(int[] A) {
// write your code here
HashMap hashMap = new HashMap();
List list = new ArrayList();
for(int i=0;i<A.length;i++) {
hashMap.put(i, A[i]);
}
HashMap hash = new HashMap();
for(int i=0;i<A.length;i++) {
if(hashMap.containsValue(A[i])) {
hashMap.remove(i);
if(hashMap.containsValue(A[i])) {
hashMap.put(i, A[i]);
} else {
return A[i];
}
}
}
return 0;
}
利用List的特性:
public static int singleNumber(int[] A) {
// write your code here
HashMap hashMap = new HashMap();
List list = new ArrayList();
for(int i=0;i<A.length;i++) {
list.add(A[i]);
}
for(int i=0;i<list.size();i++) {
int num=0;
for(int j=0;j< A.length;j++) {
if((int)list.get(i)==A[j]) {
num ++;
}
}
if(num ==1) {
return (int)list.get(i);
}
}
return 0;
}
上面兩種方式,自己瞎想的。然後看到一種很厲害的方法
通過^運算。0兩次對同一個數進行^運算,會變爲0.
public class Solution {
public int singleNumber(int[] A) {
if(A == null || A.length == 0) {
return -1;
}
int rst = 0;
for (int i = 0; i < A.length; i++) {
rst ^= A[i];
}
return rst;
}