LeeCode 442. Find All Duplicates in an Array题解

该博客介绍了LeetCode第442题的解决方案,即在一个1到n的整数数组中找出所有出现两次的元素。在O(n)的时间复杂度和不需要额外空间的情况下,通过遍历数组并重新排列元素,找出未在正确位置上的元素,即为重复的数值。
摘要由CSDN通过智能技术生成

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?

中文 :给定数组a,1<=a[i]<=n,每个元素至多出现2次,找出出现2次的元素。

解 :

因为a的大小也是n,所以如果把a看成抽屉,把抽屉i放元素i+1(下标起始不一致),那么必有抽屉必须放不为i+1的元素,找出这些抽屉输出。

如何找出这些抽屉呢?我们遍历一次数组,每次把元素i放进它对应的位置,遍历完后便有最多元素归位(数学证明略)

代码:

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> res;
        int i = 0;
        while (i < nums.size()) {
            if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]);
            else i++;
        }
        for (i = 0; i < nums.size(); i++) {
            if (nums[i] != i + 1) res.push_back(nums[i]);
        }
        return res;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值