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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//第一题,无脑超时
public class Solution {
public int singleNumber(int[] A) {
List<Integer> resultList = new ArrayList<Integer>();
List list = new ArrayList();
for(int i=0;i<A.length;i++){
Integer aiInteger = new Integer(A[i]);
if(list.contains(aiInteger)){
resultList.remove(aiInteger);
}else{
list.add(aiInteger);
resultList.add(aiInteger);
}
}
return resultList.get(0);
}
}
//查看别人算法后:按位异或,所有重复项抵消
public class Solution {
public int singleNumber(int[] A) {
int sum = 0;
for(int i = 0;i<A.length;i++){
sum^=A[i];
}
return sum;
}
}