[C++] Clean Code - 4 Solutions


  • 0

    Solution - Number of unique numbers (start 0)

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            /* 0. uniq pool size n start from 0, for each num that is not a duplicate, extend n after write to nums[n]. */
            int n = 0;
            for (int i = 0; i < nums.size(); i++) {
                if (i == 0 || nums[i] != nums[n - 1]) {
                    nums[n++] = nums[i];
                }
            }
    
            return n;
        }
    };
    

    Solution - Number of unique numbers

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if (nums.size() < 2) {
                return nums.size();
            }
    
            int n = 1;
            for (int i = 0; (n - 1) <= i && i < nums.size(); i++) {
                if (nums[i] != nums[n - 1]) {
                    nums[n++] = nums[i];
                }
            }
            
            return n;
        }
    };
    

    Solution - Index of last unique number

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if (nums.size() < 2) {
                return nums.size();
            }
    
            int j = 0;
            for (int i = 0; j <= i && i < nums.size(); i++) {
                if (nums[i] != nums[j]) {
                    nums[++j] = nums[i];
                }
            }
    
            return j + 1;
        }
    };
    

    Solution - Check Prev

    class Solution {
    public:
        int removeDuplicates(vector<int>& a) {
            long prev = LONG_MAX;
            int size = 0;
            for (int i = 0; i < a.size(); prev = a[i++])
                if (a[i] != prev)
                    a[size++] = a[i];
    
            return size;
        }
    };
    

Log in to reply
 

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