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

推荐阅读更多精彩内容