Very simple C++ solution O(n) not O(2n)


  • 0
    S
    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            vector<int> res;
            
            for(int i = 0; i < nums.size(); ++i) {
                int idx = abs(nums[i]) - 1;
                if (nums[idx] > 0) {
                    nums[idx] = -nums[idx];
                }
                else {
                    res.push_back(idx + 1);
                }
            }
            
            return res;
        }
    };
    

Log in to reply
 

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