美文网首页
Swift-Remove Duplicates from Sor

Swift-Remove Duplicates from Sor

作者: FlyElephant | 来源:发表于2017-05-31 09:51 被阅读63次

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

核心代码:

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

相关文章

网友评论

      本文标题:Swift-Remove Duplicates from Sor

      本文链接:https://www.haomeiwen.com/subject/nqqlfxtx.html