【CODE】Find All Duplicates in an Array

442. Find All Duplicates in an Array

Medium

1416126FavoriteShare

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]
  • 思路借鉴:https://www.cnblogs.com/grandyang/p/6209746.html
  • A.从头遍历,该数字应该在的地方(按升序排列)的数字如果是正数,设为他的相反数,如果是负数,则说明该数字曾经出现过:
  • Runtime: 116 ms, faster than 73.60% of C++ online submissions for Find All Duplicates in an Array.
  • Memory Usage: 14.9 MB, less than 90.00% of C++ online submissions for Find All Duplicates in an Array.
  • B.从头遍历,将数字放在该放的地方,再遍历一遍,不在该在地方的数字为重复数字(该方法需要注意第一遍遍历手段):
  • Runtime: 108 ms, faster than 96.35% of C++ online submissions for Find All Duplicates in an Array.
  • Memory Usage: 14.8 MB, less than 100.00% of C++ online submissions for Find All Duplicates in an Array.
  • C.从头遍历,将该数字应该在的地方(可能会越界,因此(nums[i]-1)%n)的数字加n,再遍历一次,如果该位置的数字大于2n,说明该位置应该放的数字有重复:
  • Runtime: 120 ms, faster than 46.12% of C++ online submissions for Find All Duplicates in an Array.
  • Memory Usage: 14.9 MB, less than 65.00% of C++ online submissions for Find All Duplicates in an Array.
  • Next challenges:
  • Word Ladder II
  • Shortest Word Distance
  • Sum of Digits in the Minimum Number
  • Find the Duplicate Number
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int i=0;
        vector<int> res;
        for(i=0;i<nums.size();i++){
            if(nums[abs(nums[i])-1]<0) res.push_back(abs(nums[i]));
            else nums[abs(nums[i])-1]*=-1;
        }
        return res;
    }
};
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int i=0;
        vector<int> res;
        for(i=0;i<nums.size();i++){
            if(nums[nums[i]-1]!=nums[i]){
                swap(nums[nums[i]-1],nums[i]);
                i--;
            }
        }
        for(i=0;i<nums.size();i++){
            //cout<<nums[i]<<endl;
            if(i+1!=nums[i]) res.push_back(nums[i]);
        }
        return res;
    }
};
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int i=0;
        vector<int> res;
        for(i=0;i<nums.size();i++){
            nums[(nums[i]-1)%nums.size()]+=nums.size();
        }
        for(i=0;i<nums.size();i++){
            if(nums[i]>2*nums.size()) res.push_back(i+1);
        }
        return res;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值