https://leetcode.com/problems/single-number-ii/description/
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解题思路:
使用HashMap存每个元素出现的次数
import java.util.Map.Entry;
public class Solution {
public int singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int result=0;
for(int i:nums){
if(!map.containsKey(i)){
map.put(i, 1);
}else{
map.put(i, map.get(i)+1);
}
}
Set<Entry<Integer,Integer>> entrySet = map.entrySet();
for(Entry es:entrySet){
int count = (Integer)es.getValue();
if(count!=3){
result = (Integer)es.getKey();
break;
}
}
return result;
}
}