Java code fails at test case #19


  • 0
    T
    public class Solution {
        
        public int removeDuplicates(int[] nums) {
            if(nums.length == 0) return 0;
            
            int counter = 1;
            int currentVal = nums[0];
            int swapIndex = 0;
            
            for(int i = 1; i < nums.length; i++) {
                if(nums[i] != currentVal) {
                    counter++;
                    swapIndex++;
                    int temp = nums[swapIndex];
                    nums[swapIndex] = nums[i];
                    nums[i] = temp;
                }
            }
            return counter;
        }
    }
    

    Could anyone help me figure out why it does not work?

    Input: [1,2,2]

    Output: [1,2,2]

    Expected: [1,2]


  • 0
    D

    public int removeDuplicates(int[] nums) {
    if(nums.length == 0) return 0;

            int counter = 1;
            int currentVal = nums[0];
            int swapIndex = 0;
    
            for(int i = 1; i < nums.length; i++) {
                if(nums[i] != currentVal) {
                    counter++;
                    swapIndex++;
                    currentVal=nums[i];//you should update  currentval
                    int temp = nums[swapIndex];
                    nums[swapIndex] = nums[i];
                    nums[i] = temp;
                }
            }
            return counter;
        }

Log in to reply
 

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