LeetCode-去除数组中重复数字

给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。

找到所有出现两次的元素。

你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> result=new ArrayList<Integer>();
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(Integer i:nums) {
            if(null == map.get(i)) {
                map.put(i, 1);
            }else {
                map.put(i, map.get(i)+1);
            }
        }

        for(Integer i:nums) {
            if(null != map.get(i) && map.get(i)>1) {
                result.add(i);
                map.remove(i);
            }
        }
        return result;
    }
}

在提交者中看到了一个执行最快10ms的代码他是这样写的:

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int[] arr = new int[nums.length+1];

        for (int i : nums) {
            arr[i]++;
        }

        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            if(arr[i]>1){
                list.add(i);
            }
        }

        return list;
    }
}

这段代码如果数组中 num[n]>nums.length+1 这段程序就会报ArrayIndexOutOfBoundsException不能够通用

猜你喜欢

转载自blog.csdn.net/BeiShangBuZaiLai/article/details/81565487
今日推荐