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性锭、默認(rèn)數(shù)組元素從小到大排列
2入愧、準(zhǔn)確定位元素新下標(biāo)(數(shù)組元素刪除導(dǎo)致此之后的元素下標(biāo)靠前一位)
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
在上一個(gè)版本的基礎(chǔ)上添加一個(gè)變量,記錄當(dāng)前數(shù)字的重復(fù)次數(shù)
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
}
}