Share my 20-ms solution in C++


  • 0
    E
    class Solution {
    public:
    	int removeDuplicates(int A[], int n) {
    		int count = 0;
    		int i = 0;
    		int cmp;
    		if (n <= 1){
    			return n;
    		}
    		while (i < n - 1) {
    			if (A[i] != A[i + 1]){
    				A[count++] = A[i++];     // save the non-duplicates
    			}
    			else {
    				cmp = A[i];
    				A[count++] = A[i++];     // only save two duplicates
    				A[count++] = A[i++];
    				while (A[i] == cmp){      // skip the rest of the duplicates
    					i++;
    				}
    			}
    		}
    		if (count > 0 && i < n && A[i] != A[count - 1]) { // deal with the last element
    			A[count++] = A[i];
    		}
    		return count;
    	}
    };

Log in to reply
 

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