【Leetcode】442. Find All Duplicates in an Array

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]

Subscribe to see which companies asked this question.

题目简述:

输入一个数组,数组中元素满足 1 ≤ a[i] ≤ n ,输入数组中出现两次的元素。

要求:不能使用额外空间,时间复杂度O(n)

思路简述:

step 1 想到利用数组中索引的信息,按顺序读取数组,假设本轮读取到的数字为A,如果A = -1 或者 A指向自己位置则跳过。

step2 访问数字A对应位置的元素,如果该元素与A相同,将该位置元素置-1,表示A出现过两次。返回step 1。

step3 重新访问数组,-1元素对应的索引+1就是出现两次的元素。


代码:

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        for(int i=0;i<nums.length;){
            int temp = 0;
            if(nums[i] <=0 || nums[i]-1 == i){
                i++;
            }else if(nums[nums[i]-1]!=-1 &&nums[nums[i]-1] != nums[i] ){
                temp = nums[nums[i]-1];
                nums[nums[i]-1] = nums[i];
                nums[i] =temp;
            }else{
                nums[nums[i]-1] = -1;
                i++;
            }
        }
        for(int i=0;i<nums.length;i++){
            if(nums[i] == -1){
                res.add(i+1);
            }
        }
        return res;
    }
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值