Java solution by counting the shift space


  • 0
    S
    public class Solution {
        public int removeDuplicates(int[] A) {
            int shift_count=0;
            if(A.length<2){
                return A.length;
            }
            int cur_int=A[0];
            for(int i=1;i<A.length;i++){
                if(A[i]==cur_int){
                    shift_count++;       // if it is a duplicate shift_count plus one
                }else{
                    cur_int=A[i];
                }
                A[i-shift_count]=A[i];   // no matter duplicate or not, shift every time with the shift count
            }
            return A.length - shift_count;
        }
    }

  • 0
    H

    Pretty like mine, but I record position to for the next replacement rather then the shift length.

    public int removeDuplicates(int[] A) {
        int len = A.length;
        if(len < 2) {
            return len;
        }
        int pos = 1;
        for(int i = 1; i < len; i++) {
            if(A[i] != A[i - 1]) {
                A[pos++] = A[i];
            }
        }
        return pos;
    }
    

Log in to reply
 

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