3、Remove Duplicates from Sorted Array

Problem Description

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 nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.

Analyze

1、默認數組元素從小到大排列
2、準確定位元素新下標(數組元素刪除導致此之后的元素下標靠前一位)

Code

class Solution {
    func removeDuplicates(inout nums: [Int]) -> Int {
        var removedCount = 0
 
        for (index, num) in nums.enumerate() {
             if index == 0 { continue }
             
            if num == nums[index - 1 - removedCount] {
                nums.removeAtIndex(index - removedCount)
                removedCount += 1
            }
        }
        return nums.count
    }
}

Remove Duplicates from Sorted Array II(Medium)

Problem Description

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

Analyze

在上一個版本的基礎上添加一個變量,記錄當前數字的重復次數

Code

class Solution {
    func removeDuplicates(inout nums: [Int]) -> Int {
        var duplicatesCount = 0
        var removedCount = 0
        for (index, num) in nums.enumerate() {
            if index == 0 { continue }
            
            if num == nums[index - 1 - removedCount] {
                duplicatesCount += 1
                if duplicatesCount > 1 {
                    nums.removeAtIndex(index - removedCount)
                    removedCount += 1
                }
                continue
            }
            
            duplicatesCount = 0
        }
        return nums.count
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容