leetcode 442. Find All Duplicates in an Array

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]

根据题目要求,不能用多余的内存,考虑到a[i]<=n 所以数组nums本身就是个0~n-1 的hash表,通过标记num[index]有没有被2次访问过,来统计哪些数字出现两次。

考虑到nums[index]被标记后,还得继续使用,所以采用负号标记最好

注意题目没有要求结果必须按照由小到大的顺序输出

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int>v;
        for (int i = 0; i < nums.size(); ++i) {
            int index = abs(nums[i]) - 1;
            if (nums[index] < 0) v.push_back(index + 1);
            nums[index] = -nums[index];
        }
        return v;
    }
};
原文地址:https://www.cnblogs.com/pk28/p/7341712.html