Java Share my O(n) time and O(1) space solution to deal with the number of deleted


  • 0
    Q
     public static int removeDuplicates(int[] nums) {
            int count=0; //used to save the number of arrays
            if(nums==null||nums.length==0) return count;
            if(nums.length<=2) return 2;
            count=1;
            int k=1;//set a tag
            for(int i=1;i<nums.length;i++){
                if(k<2){ //match the number of deleted
                    if(nums[i]==nums[i-1]){
                        nums[count++]=nums[i];
                        k++;
                    }else {
                        //move and restore k value
                        nums[count++]=nums[i];
                        k=1;
                    }
                }else {// not match the number of deleted
                    if(nums[i]!=nums[i-1]){
                        //move and restore k value
                        nums[count++]=nums[i];
                        k=1;
                    }else {
                        //not match k ++
                        k++;
                    }
    
                }
            }
            return count;
    

Log in to reply
 

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