Swift 3 linear solution


  • 1
    Y
    class Solution {
        // 23ms 100%
        // two pointers slow and fast 
        // time: O(n), space: O(1)
        func removeDuplicates(_ nums: inout [Int]) -> Int {
            let len = nums.count
            if len <= 2 {
                return len
            }
            
            var slow = 1
            for fast in 2..<len {
                // nums[slow] != nums[slow - 1] to allow at most twice duplicates
                if nums[slow] != nums[fast] || nums[slow] != nums[slow - 1] {
                    slow += 1 
                    nums[slow] = nums[fast]
                } 
            }
            return slow + 1
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.