Simple Swift solution with O(n) and one pointer


  • 0
    S
    func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
            var cur = 0
            for i in 0..<nums.count {
                if nums[i] != val {
                    nums[cur] = nums[i]
                    cur += 1
                }
            }
            return cur
        }
    

    The idea here is to take a pointer cur, initially at 0. If the element is not equal to val, just move the element to the index that is cur, and increment cur. In the end, return cur. This way, all elements not equal to cur will be moved to the beginning.


Log in to reply
 

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