java solution with explain


  • 0
    W

    set a new index of the arrays (copy_index), only when the duplicate over 2 copy_index --. when traversing the nums, we assign the current index's value to copy_index' value

    '''public class Solution {
    public int removeDuplicates(int[] nums) {
    if (nums.length <= 2){
    return 2;
    }

        boolean jump = false;
        int copy_index = 1;
        int t = nums[0];
        int counter = 0;
        for (int i = 1; i < nums.length; i++){
            nums[copy_index++] = nums[i];
            if (nums[i] == t){
                
                if (jump){
                    counter ++;
                    copy_index --;
                    
                }else{
                    jump = true;
                    
                }
            }
            else {
                
                t = nums[i];
                jump = false;
            }
        }
        return nums.length - counter;
    }
    

    }'''


Log in to reply
 

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