Leetcode-442. Find All Duplicates in an Array-思路详解-C++

本文介绍了一个在整数数组中查找重复元素的算法,该数组中所有元素的范围在1到n之间,部分元素出现两次,其余元素仅出现一次。文章详细阐述了如何在O(n)的时间复杂度内且不使用额外空间的情况下实现这一任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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 < a[i] <= n,(n为数组的大小),一些元素出现了一次,一次出现了两次。
在数组中找出出现了两次的元素。

要求:
不适用额外的空间,且时间复杂度为O(n)

思路

该题目和 448 - Find All Numbers Disappeared in an Array是相互对偶的题目。448 -Find All Numbers Disappeared in an Array是寻找没有出现的数,该题目是寻找出现了两次的数。

思路类似。
注:
1,首先从前往后遍历。
2,如果第i处的值,等于i。跳过处理下一个。
3,如果第i处的值,不等于i,则和nums[i]-1处的数据进行交换。如果交换的值和被交换的值相同,则说明找到一个出现两次的值。将该值存入结果,并将被交换处置为0。如果不相等,则交换。

代码

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int len = nums.size();
        vector<int> res;
        while(!isUp(nums)){
            for(int i = 0;i < len; i++){
                //如果元素值不等于索引值,则交换到元素应该在的位置上
                if(nums[i]!= 0 && nums[i]-1 != i){
                    if(nums[nums[i] - 1] == nums[i] ){
                        res.push_back(nums[i]);
                        nums[i] = 0;
                    }else{
                        int tmp = nums[nums[i]-1];
                        nums[nums[i]-1] = nums[i];
                        nums[i] = tmp;
                    }
                }
            }
        }

        return res;
    }

    bool isUp(vector<int> &nums){
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] != 0 && nums[i] != i+1){
                return false;
            }
        }

        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值