Swift-Remove Duplicates from Sorted Array

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
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 一 姥姥的父亲去世的早,母亲改嫁,姥姥的带着两个弟弟,后来辗转到姥爷村里,那个年代谈爱情是奢侈,但打小我就有一种感...
    大宝在路上阅读 4,270评论 6 7
  • 以前也经常广州深圳来回,总是来又走,以前总觉得自己是两个城市的孩子。后来爸爸总爱提醒我不是城里人,就是乡下的穷农民...
    空瑾阅读 1,072评论 0 0