题目描述
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
package offer;
import java.util.HashMap;
import java.util.Map;
public class singleNumberII {
public int singleNumber(int[] A) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < A.length; i++){
if(!map.containsKey(A[i])){
map.put(A[i], 1);
}else{
int k = map.get(A[i]);
if(k == 2){
map.remove(A[i]);
}
map.put(A[i], ++k);
}
}
return map.keySet().iterator().next();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] B = {1,2,2,3,3,2,3,1,1,5};
singleNumberII ss = new singleNumberII();
System.out.println(ss.singleNumber(B));
}
}
输出结果应为:5
结果为: 1
Map.put(a[i],k++)应该放在else里面,否则你刚remove掉了,然后就又put进去了
题目要求不允许用多余的存储空间,你直接用map是不行的