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
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • 一 姥姥的父親去世的早,母親改嫁,姥姥的帶著兩個弟弟,后來輾轉(zhuǎn)到姥爺村里,那個年代談愛情是奢侈,但打小我就有一種感...
    大寶在路上閱讀 859評論 6 7
  • 以前也經(jīng)常廣州深圳來回,總是來又走,以前總覺得自己是兩個城市的孩子。后來爸爸總愛提醒我不是城里人,就是鄉(xiāng)下的窮農(nóng)民...
    空瑾閱讀 162評論 0 0