Keeping track of the counts of each element | C++ Solution O(n) time and O(1) space


  • 0
    H
    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            vector<int> ans;
            int count, value;
            for(int i = 0; i < nums.size(); i++) {
                nums[i] *= 3;
            }
            for(int i = 0; i < nums.size(); i++) {
                value = nums[i] / 3;
                nums[value - 1]++;
            }
            for(int i = 0; i < nums.size(); i++) {
                count = nums[i] % 3;
                if (count == 2) ans.push_back(i + 1);
                nums[i] = nums[i] / 3;
            }
            return ans;
        }
    };
    

Log in to reply
 

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