26. Remove Duplicates from Sorted Array
Contents
Automatic Translation
This article has been translated automatically from Russian to English. The original is available in Russian.
Solution to problem 26 “Remove Duplicates from Sorted Array” from LeetCode.
Problem Statement
Given a sorted array of numbers nums. You need to remove duplicates inside this array and return the new length of the array. You cannot allocate space for a new array.
Example 1
nums = [1,1,2],
Function should return `2`. That is, the zeroth and first elements of the array should be `1` and `2` respectively.
It doesn't matter what comes after in the arrayExample 2
nums = [0,0,1,1,1,2,2,3,3,4],
Function should return `5`. The first five elements of the array should be 0,1,2,3,4 and 5.
It doesn't matter what comes after in the arraySolution
Two Pointers
Algorithm idea:
There are two pointers:
- The first looks at the current element (at each step it moves to the next element)
- The second looks at the last non-repeating element
When the element at the current pointer becomes greater than the element at the second pointer:
- Move the second pointer to the next element
- Assign to the address of the second pointer the value from the current pointer
Return second pointer + 1
func removeDuplicates(nums []int) int {
if len(nums) <=1 {
return len(nums)
}
lidx :=0
for idx:=1;idx <len(nums);idx++ {
if nums[idx] > nums[lidx] {
lidx ++
nums[lidx] = nums[idx]
}
}
return lidx+1
}