136. Single Number - LeetCode
阿新 • • 發佈:2018-06-17
problem i++ span pre key 遍歷數組 ddn bre ret
Question
136.?Single Number
Solution
思路:構造一個map,遍歷數組記錄每個數出現的次數,再遍歷map,取出出現次數為1的num
public int singleNumber(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int i=0; i<nums.length; i++) {
Integer count = countMap.get(nums[i]);
if (count == null ) {
count = 0;
}
countMap.put(nums[i], count + 1);
}
int num = -1;
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
num = entry.getKey();
break;
}
}
return num;
}
136. Single Number - LeetCode