442. Find All Duplicates in an Array--找到数组中出现两次的数字

来源:互联网 发布:网络三字经全文解释 编辑:程序博客网 时间:2024/06/05 11:00

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]

题目的意思很明显了,找到数组中出现次数为2的数字,返回这些数字即可。我用了HashMap,将每个数字和它出现的次数作为一个映射,然后遍历map,将符合条件的值添加到list中即可。虽然AC了,但是只击败了4.8%的提交结果==,代码如下:

        List<Integer> list = new ArrayList<Integer>();        Map<Integer,Integer> map = new HashMap<>();        for(int i=0;i<nums.length;i++){        if(!map.containsKey(nums[i])){        map.put(nums[i], 1);        }        else{map.put(nums[i],map.get(nums[i])+1);}                }        for(Map.Entry<Integer,Integer> m:map.entrySet())              if(m.getValue()==2){            list.add(m.getKey());            }        return list;
网上看了另一种方法,充分应用条件,因为题目中说明,这些数字1 ≤ a[i] ≤ n (n = size of array),并且一些数字出现2次,其他的出现1次,那么,新建一个数组,把nums中的数字nums[i]放到temp中索引为nums[i]的地方,如果temp[nums[i]]=nums[i],说明nums[i]之前已经出现过,那么就将它加入到res这个列表中,提交结果为60%左右。代码如下:

    int [] temp = new int [nums.length+1];List<Integer> res = new ArrayList<>();for(int i=0;i<nums.length;i++){if(temp[nums[i]]==nums[i]){res.add(nums[i]);}else{temp[nums[i]]=nums[i];}}return res;


阅读全文
0 0
原创粉丝点击