leetcode 442. Find All Duplicates in an Array(找出重复元素)

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]

给出一个数组,数组的元素是1~n范围内的数字,元素会出现1次或2次,找出出现2次的元素

思路:
因为不要有extra space而且是O(n) time。因此考虑在原数组上做,元素的范围在1~n,可以考虑把每个元素放到它对应的index的位置上,比如1就放在第1个,n放在最后一个。

遍历数组,调换位置,把元素放在应该在的位置。期间可能调换时会发现对应的index上已经是该元素,但这时不要把结果保存,因为可能重复,到全部调换完成之后,看对应位置上对不上的,就是结果。
比如[4,3,2,7,8,2,3,1]调换完后是[1, 2, 3, 4, 3, 2, 7, 8],找出nums[i] != (i+1)的保存到结果

注意:调换顺序时要先让nums[nums[i]-1] = nums[i]; 因为一旦nums[i]发生变化,后面nums[nums[i]-1]就不是正确的数字。

    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> result = new ArrayList<>();
        
        if(nums == null || nums.length <= 1) {
            return result;
        }
        
        int n = nums.length;
        
        for(int i = 0; i < n; i++) {
            
            while(nums[i] != (i+1)) {
                if(nums[i] == nums[nums[i]-1]) {
                    break;
                }
                int tmp = nums[nums[i]-1];
                nums[nums[i]-1] = nums[i];
                nums[i] = tmp;
            }
        }
        
        for(int i = 0; i < n; i ++) {
            if(nums[i] != (i+1)) {
                result.add(nums[i]);
            }
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值