Remove duplicates from sorted array I and II, C++ solution, easy to understand


  • 0
    X

    Remove duplicates from sorted array I:

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

    Remove duplicates from sorted array II:

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

Log in to reply
 

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