[LeetCode]442. Find All Duplicates in an Array

Description:

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]
————————————————————————————————————————————————————————————————————————————

Solution:

题意:找到在给定数组中仅出现两次的元素(最多也只出现两次)。

思路:注意到数组元素的共同特性:1<=a[i]<=n,这意味着如果没有重复元素,那么整个数组将是恰好由1,2,3,...,n组成的。

那么我们只需要遍历一遍数组,判断当元素值为i时,数组第i+1个(数组从0开始因此要加一)元素值是否也为i,(前提是该元素值不为-1或i+1),若不等,则将该元素与第i+1个元素交换,继续判断;若相等,则说明出现值为i的重复元素,将该重复元素压入结果数组中,同时将两元素值设为-1(用于判断i值是否已经判断过了)。遍历结束,得到结果。

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int curIndex = 0;
        vector<int> result;
        
        for (int i = 0; i < nums.size(); i++) {
            while (nums[i] != i + 1 && nums[i] != -1) {
                if (nums[nums[i] - 1] == nums[i]) {
                    result.push_back(nums[i]);
                    nums[nums[i] - 1] = -1;
                    nums[i] = -1;
                } else {
                    int temp = nums[nums[i] - 1];
                    nums[nums[i] - 1] = nums[i];
                    nums[i] = temp;
                }
                /*
                cout << i << ". ";
                for (int j = 0; j < nums.size(); j++)
                    cout << nums[j] << " ";
                cout << endl;
                */
            }
        }
        
        sort(result.begin(), result.end());
        return result;
    }
};

更简便的方法是不需要第二层循环,将nums[nums[i]-1]设为负数,这样只需要一层循环就可以找到所有重复的元素。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值