Problem Statement
Given an integer array
nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements innums
.
…
Approach
- Keep a pointer to the last unique element. Set it to 0 initially.
- Iterate through the array from the second element.
- If the current element is different from the last unique element, increment the pointer. Set the element at pointer equal to the current element.
- Continue until the end of the array.
- The number of unique elements is the pointer + 1.
Solution in Swift
class Solution {
func removeDuplicates(_ nums: inout [Int]) -> Int {
guard nums.count > 1 else { return nums.count }
var lastUniqueIndex = 0
for currentIndex in 1..<nums.count where nums[currentIndex] != nums[lastUniqueIndex] {
lastUniqueIndex += 1
nums[lastUniqueIndex] = nums[currentIndex]
}
return lastUniqueIndex + 1
}
}
Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(1)\)