Swift solution - Two Pointers


  • 0
    class Solution {
        func removeDuplicates(_ nums: inout [Int]) -> Int {
            let k = 2
            
            if nums.count <= 2 {
                return nums.count
            }
            
            var i = 1
            var j = 1
            var count = 1
            
            while j < nums.count {
                if nums[j] != nums[j - 1] {
                    count = 1
                    nums[i] = nums[j]
                    i += 1
                } else {
                    if count < k {
                        nums[i] = nums[j]
                        i += 1
                        count += 1
                    }
                }
                j += 1
            }
            
            return i
        }
    }
    

Log in to reply
 

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