欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]442. Find All Duplicates in an Array

程序员文章站 2024-02-17 12:08:22
...

[leetcode]442. Find All Duplicates in an Array


Analysis

周五ummmmmm—— [啊啊啊啊 paper结果要出来了,心塞]

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?

Implement

方法一(先排序,然后找出现了两次的)

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<int> res;
        if(nums.size() == 0)
            return res;
        for(int i=0; i<nums.size()-1; i++){
            if(nums[i] == nums[i+1])
                res.push_back(nums[i]);
        }
        return res;
    }
};

方法二(把相应位置变为相反数,如果某一位变成了正数,则说明其改变了两次,即为duplicates,一般在遇到1 ≤ a[i] ≤ n (n = size of array)这种情况都可以这样做~)

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> res;
        int n = nums.size();
        for(int i=0; i<n; i++){
            nums[abs(nums[i])-1] = -nums[abs(nums[i])-1];
            if(nums[abs(nums[i])-1] > 0)
                res.push_back(abs(nums[i]));
        }
        return res;
    }
};
相关标签: leetcode