[leetcode 442] Find All Duplicates in an Array

本文介绍了一种在整数数组中查找重复元素的算法,利用数组元素的特定范围1≤a[i]≤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的限制条件,所以整个算法就是在使得a[i] = i+1。具体的,遍历每个位置,将不属于该位置的元素归位,如果该元素理应存在的位置已经有一个正确的元素,那么就出现重复,将重复元素废弃(将值设为一个非法值如-1)。整个算法做了遍历操作(O(N))以及将元素归位(O(N)),所以整体也是O(N)。

代码

    void swap(int& a,int& b) {
        int c = a;
        a = b;
        b = c;
    }
    vector<int> findDuplicates(vector<int>& nums) {
        int s = nums.size();
        vector<int> result;
        for (int i = 0;i < s;++i) {
            while (nums[i] != -1 && nums[i] != i+1) {
                if (nums[nums[i]-1] == nums[i]) {
                    result.push_back(nums[i]);
                    nums[i] = -1;
                }
                else 
                    swap(nums[i],nums[nums[i]-1]);
            }
        }
        sort(result.begin(),result.end());
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值