Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1]
Output: [2,3]
class Solution {
public List<Integer> findDuplicates(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
List<Integer> list = new ArrayList<>();
for(int x : nums){
if(map.containsKey(x)){
map.put(x, 2);
continue;
}
else map.put(x, 1);
}
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
for(Map.Entry<Integer, Integer> x : entrySet){
if(x.getValue() == 2)
list.add(x.getKey());
}
return list;
}
}
总结
- HashMap的put()函数和replace()函数都可以用于替换相同Key的Value,不同点就是,put对于不存在的Key会新建一个,而replace对于不存在的Key则不采取行动
- HashMap的遍历有几种形式,如keySet()和entrySet(),前者输出的是Key类的Set集合,后者输出的是Map.Entry<>类的Set集合;因为是Set集合所有存在迭代器,所有就可以遍历了。两者的调用方式也不一样,Key类的用Map类实例的.get(key),Map.Entry<>类的用其具体实例的.getKey()和.getValue()。详见Map集合中value()方法与keySet()、entrySet()区别