Simple C++ implementation


  • 0

    At my first implementation I got WA, so why ?

    The problem is that we need to make it clear how to use the count and what the count means.

    For every new number, count=1 means it appears for 1 time, if every number can appear for no more than

    2 times, so we can check

      if(count<2)
    

    Here is the AC code:

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int len=nums.size();
            if(len<=2)  return len;
            int count=1;
            int start=0, end=1;
            while(end<len){
                if(nums[end]!=nums[start]){
                    nums[++start]=nums[end++];
                    count=1;
                }
                else{
                    if(count<2){
                        nums[++start]=nums[end];
                        count++;
                    }
                    end++;
                }
            }
            return start+1;
        }
    };

Log in to reply
 

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