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
}
}