Remove Duplicates from Sorted Array I


Description:

Given a sorted array, remove the duplicates in place such that each element appear onlyonceand return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

EXAMPLE:

Input array: [1, 1, 2]

Output the length (2) of an array with all duplicates removed ([1, 2])

Solution

Since the array is sorted, the same elements must lay next to each other.

  • Time: O(n)
public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length == 0) return 0;
        int j = 0; 
        for(int i = 1; i < nums.length; i ++) {
            if (nums[i] != nums[j]) {
                nums[++j] = nums[i];
            } 
        }
        return j+1;
    }
}

results matching ""

    No results matching ""