One pass C++ solution


  • 0
    F
        vector<int> findDuplicates(vector<int>& nums) {
            vector<int> ans;
            // 0 - empty slot
            for(int i=0; i<nums.size(); ++i) {
                while(nums[i] != 0 && nums[i] != i+1) {
                    if(nums[i] == nums[ nums[i] - 1]) {
                        ans.push_back(nums[i]);
                        nums[i] = 0;
                        break;
                    }
                    swap(nums[i], nums[ nums[i] - 1]);
                }
            }
            return ans;
        }

Log in to reply
 

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