Leetcode 442. Find All Duplicates in an Array

weixin_34019929發表於2018-07-27

文章作者:Tyan
部落格:noahsnail.com  |  CSDN  |  簡書

1. Description

3232548-ff57350fc2343e4b.png
Find All Duplicates in an Array

2. Solution

  • O(n), O(n)
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> result;
        if(0 == nums.size()) {
            return result;
        }
        int flag[nums.size()] = {0};
        for(int i = 0; i < nums.size(); i++) {
            if(flag[nums[i]]) {
                result.push_back(nums[i]);
            }
            else {
                flag[nums[i]] = 1;
            }
        }
        return result;
    }
};
  • O(n), O(1)
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> result;
        if(0 == nums.size()) {
            return result;
        }
        for(int i = 0; i < nums.size(); i++) {
            int index = abs(nums[i]) - 1;
            if(nums[index] < 0) {
                result.push_back(abs(nums[i]));
            }
            nums[index] = - nums[index];
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/find-all-duplicates-in-an-array/description/

相關文章