C++ simple solution


  • 0

    explanation:
    since 1 ≤ a[i] ≤ n, we can use the index of the vector
    index-0-1-2-3-4-5
    num--1-2-3-4-5-6

    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            int n = nums.size();
            vector<int> res;
            for (int i = 0; i < n; i++) {
                if (nums[i] == -1 || nums[i] == i + 1)
                    continue;
                int num = nums[i];
                if (num != i + 1 && nums[num - 1] == num) {
                    res.push_back(num);
                    nums[i] = -1;
                } else {
                    swap(nums[i], nums[num - 1]);
                    i--;
                }
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.