top of page
Writer's pictureHui Wang

79. Interview: Remove Duplicates from Sorted Array (LeetCode Easy)




Train of thought:


We can NOT use any extra space, so we can't use a dictionary to remove the duplicates. Instead, we can use the Two-pointer technique: one slow-runner and the other fast-runner.


We can go through the array to see if the values pointed to by two pointers that are next to each other are the same. If they are not the same, the two are not repeated, and the value of the second pointer is put into the maintained subscript. If equal, don't need to handle.


We need to pay attention to the subscript out of bounds.

  • Time complexity: O(n)

  • Space complexity: O(1)


My answer:


class Solution {
    func removeDuplicates(_ nums: inout [Int]) -> Int {
        if nums.isEmpty { return 0 }
        var startIndex = 0
        for index in 0..<nums.count - 1 {
            if nums[index] != nums[index + 1] {
                startIndex += 1
                nums[startIndex] = nums[index + 1]
            }
        }
        return startIndex + 1
    }
}

 

Follow me on:

Comments


bottom of page