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