Remove Duplicates from Sorted Array II
Medium
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given 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 respectively.
It doesn’t matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn’t matter what values are set beyond the returned length.
题意
删除有序数列中重复的数字,每个不同的数字最多只保留两个实例
思路
用pre记录上一个数字,用cnt记录当前数字重复的次数,用place记录当前数字应该移动的位置。数列去重O(n)时间复杂度的算法的的关键是记录位置,每次只移动当前数字实例,而不要把删除数字后面的所有数字都向前移动。具体思路见代码。
代码
func removeDuplicates(nums []int) int {
n := len(nums)
if (n == 0) {
return 0
}
pre := nums[0]
cnt := 1
place := 1
for i:=1; i<n; i++ {
if nums[i] == pre {
cnt++
} else {
pre = nums[i]
cnt = 1
}
if cnt <= 2 {
nums[place] = pre
place++
}
}
return place
}