C++ simple AC solution in 10 lines 21ms


  • 9
    B
    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            if (n <= 2)
                return n;
            int rear = 1;
            for(int i = 2; i < n; i++){
                if(!(A[i] == A[rear] && A[i] == A[rear -1])){
                    A[++rear] = A[i];
                }
            }
            return rear+1;
        }
    };

  • -1
    B

    public int removeDuplicatesTwice(int[] nums){
    if (nums.length==0)
    return 0;
    int count=1;
    boolean flag=false;
    for (int i=1;i<nums.length;i++){
    if (nums[i]==nums[i-1]){
    if (!flag){
    nums[count++]=nums[i];
    flag=true;
    }
    // else
    //
    }
    else{
    flag=false;
    nums[count++]=nums[i];
    }

        }
        return count;
    }

  • 1
    R

    After see the top hot solution , i think the condition of

    if(!(A[i] == A[rear] && A[i] == A[rear -1]))

    can just be

    if (A[i] != A[rear -1])


Log in to reply
 

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