Leetcode 442. 数组中重复的数据

文章介绍了如何在给定的整数数组中找到重复的元素。提供了两种解决方案,一种是通过将找到的元素取反来标记,另一种是使用模板方法,通过交换元素来找出重复值。这两种C++代码实现都避免了考虑0的情况。

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

题目

在这里插入图片描述
Leetcode 442. 数组中重复的数据

代码(首刷自解)

这题和Leetcode 剑指 Offer 03. 数组中重复的数字不一样的地方在于,这题不需要考虑0,所以可以直接乘以-1。

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> res;
        for(int& n : nums) {
            if(nums[abs(n)-1] < 0) {
                res.push_back(abs(n));
            } else {
                nums[abs(n)-1] *= -1;
            }
        }
        return res;
    }
};

当然也能用模板方法解,for套while

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> res;
        int n = nums.size();
        for(int i = 0; i < n; i++) {
            while(nums[i] != nums[nums[i]-1]) {
                swap(nums[i], nums[nums[i]-1]);
                }
        }
        for(int i = 0; i < n; 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、付费专栏及课程。

余额充值