Remove Duplicates from Sorted Array
Problem statement
nums is sorted non-decreasing. Compact it so each value shows up once, still sorted, and return how many unique values remain. Extra slots at the end can be anything.
Example:
Input:
nums = [1, 1, 2]
Expected output:
length 2, nums begins [1, 2, ...]
Practice on LeetCode: Remove Duplicates from Sorted Array
Golang Solution
func removeDuplicates(nums []int) int {
if len(nums) <= 1 {
return len(nums)
}
i, j := 0, 1
for i < len(nums)-1 && j < len(nums) {
if nums[i] == nums[j] {
j += 1
} else {
i += 1
nums[i] = nums[j]
}
}
return i+1
}
