Remove Duplicates from Sorted Array

Problem

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

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

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

Solution

O(n) time O(1) space

public class Solution {
    public int removeDuplicates(int[] nums) {
        int index = 0;
        for (int num: nums) {
            if (index == 0 || num > nums[index - 1]) nums[index++] = num;
        }
        return index;
    }
}

Analysis

A typical remove duplicates problem
Since the given array is already sorted, we can just use one single pass to finish it
We have a var index and compare num from enhanced loop with nums[index - 1]
As long as there is no duplicates, num > nums[index - 1] must return true
Hence we use if statement to set the nums and update index by increment one

results matching ""

    No results matching ""