The blog for Design Patterns, Linux, HA and Myself!
This document presents the solution to the problem 80. Remove Duplicates from Sorted Array II - Leetcode.
[1, 1, 1, 2] becomes [1, 1, 2, 1]
1 is moved to the rightcurrent - current element in the loopcurrentCount - the number of times the current element is found consecutivelyduplicateStartIndex & duplicateEndIndex - continuous range inside the array that holds the duplicate elementThe solution involes:
current: -1currentCount: -1duplicateStartIndex: -1duplicateEndIndex: -1
idx pointing to value 0 which is @ index 0.
current contains 0 and currentCount becomes 1.duplicateStartIndex and duplicateEndIndex remain uninitialized because no duplicates have been found.current remains 0 and we increment the currentCount to 2 because 0 has been found twice consecutively.
current updates to 1 with currentCount updating to 1. We’ve not found any duplicates until now.
current remains 1 with currentCount updating to 2. We’ve not found any duplicates until now.
current remains 1 with currentCount updating to 3. We’ve found the first duplicate element.duplicateStartIndex and duplicateEndIndex point to 4th index of the nums array
current remains 1 with currentCount updating to 4. We’ve found the 2nd duplicate element.duplicateEndIndex point to 5th index of the nums array
current becomes 2 with currentCount updating to 1.duplicateStartIndex
duplicateStartIndex and duplicateEndIndex to point the correct range of elements containing the duplicate elements.
current remains 2 with currentCount updating to 2.duplicateStartIndex
duplicateStartIndex and duplicateEndIndex:
Exit Conditions
Please do provide some comments if you find the explanation a bit lacking.
func removeDuplicates(nums []int) int {
current := -1
currentCount := 0
duplicateStartIndex := -1
duplicateEndIndex := -1
for idx, num := range nums {
if num != current {
current = num
currentCount = 1
} else if num == current {
currentCount++
}
if currentCount > 2 {
if duplicateStartIndex == -1 {
duplicateStartIndex = idx
duplicateEndIndex = idx
} else {
duplicateEndIndex = idx
}
} else if currentCount <= 2 && duplicateStartIndex != -1 {
swap(nums, idx, duplicateStartIndex)
duplicateStartIndex++
duplicateEndIndex++
}
if idx == len(nums)-1 {
if duplicateStartIndex != -1 {
return len(nums) - (duplicateEndIndex - duplicateStartIndex + 1)
}
return len(nums)
}
}
return 0
}
func swap(nums []int, i, j int) {
temp := nums[i]
nums[i] = nums[j]
nums[j] = temp
}