Simple 1ms Java Solution


  • 9
    D
    public class Solution
    {
        public int removeDuplicates(int[] nums)
        {
            int dupes = 0;
            
            for (int i = 1; i < nums.length; i++)
            {
                if (nums[i] == nums[i - 1])
                    dupes++;
                
                nums[i - dupes] = nums[i];
            }
            
            return nums.length - dupes;
        }
    }

  • 0
    G

    I have test your code, but, outcoming is runtime error. Why?


  • 0
    D

    Are you testing it on LeetCode? If so, what custom tests did you run?


  • 0
    G

    en, such as [1 1 2], [1 2 3 4 4],[1 2 2 ]. All is runtime error.


  • 0
    D

    The Runtime Error is caused by your putting the custom test case in incorrectly. Your test cases should be typed as [1,1,2], [1,2,3,4,4], and [1,2,2]. You can also only have 1 test per run.


  • 0
    G

    Well done, thanks very much, the problem is solved~~


  • 0
    R
    public static int removeDuplicates(int[] nums){
    	int numUnique = nums.length-1;
    	for (int i=0; i<nums.length-1; i++) {
    		int j=numUnique;
    		while(i<j){
    			if (nums[i]==nums[j]) {
    				//swap jth with the last item
    				//let all duplicated item in behind.
    				int temp = nums[numUnique];
    				nums[numUnique] = nums[j];
    				nums[j] = temp;
    				numUnique--;
    			}	
    			j--;
    		}
    	}
    	return numUnique+1;
    }
    

  • 0
    N

    really brilliant idea, and it's one perfect solution!


Log in to reply
 

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