Remove Duplicates from Sorted Array

Question:

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.

Difficulty: Easy

Similar Problem: Remove Element

Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/


Solution:

80% SAME AS "REMOVE ELEMENT". In this solution, we will put the duplicate element forward instead of swapping any element.

Scan the array, there are two kinds of situations. One is the latter number same as the former number, and we will move scanner to the next. While if it's different, that means we found the one need to put forward. So just put the number forward, which is pointed by another pointer (let's say "marker"). Don't forget to calculate the length, which should be started from 1 (there's at least one element in the new array).

Code:

public class Solution {
    public int removeDuplicates(int[] nums) {
        int newLen = 1;
        int scanner = 1;
        int marker = 0;
        for(;scanner<nums.length;scanner++){
            if(nums[scanner] != nums[marker]){
                marker++;
                nums[marker] = nums[scanner];
                newLen++;
            }
        }
        return newLen;
    }
}

results matching ""

    No results matching ""