Article directory
80. Remove Duplicates in Sorted Array II
topic
Given an ordered array
nums
, please原地
delete repeated elements so that elements that appear more than twice appear only twice, and return the new length of the array after deletion.Don't use extra array space, you have to modify the input array in-place and do so while using
O(1)
extra space.
problem solving ideas
My idea is roughly as follows, use three independent indexes (pointers) i,j,k
, the index i
is used to point to the last element of the last element of the result array, the index j
is used to point to the first element of each repeat segment, and the index k
is used to point to each repeat The next element of the paragraph. Therefore, k-j
it is the number of identical elements in each repeated segment. By judging the number of repetitions, move the index i
to perform mobile assignment (if the number is 1, assign once; if the number is greater than or equal to 2, assign twice). After each move assignment is completed, j = k
assign k
the value to j
, so that it j
points to the first element of the next segment. And so on, until the penultimate repeated segment is traversed. For the last repeating segment, because the head index of the next repeating segment cannot be found k
, the length of the last repeating segment cannot be obtained, and thus cannot be judged. Therefore, it is necessary to calculate the length of the last repeated segment separately, and perform index i
movement assignment separately. My rookie solution is as follows (thought for a long time www):
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
n = len(nums)
if n == 0 or n ==1:
return n
# nums[0,i]为非重复数列
i = 0
j = 0
k = j + 1
while k <= n-1:
if nums[j] != nums[k]:
if k - j == 1:
nums[i] = nums[j]
i += 1
elif k - j >= 2:
nums[i] = nums[j]
nums[i+1] = nums[j]
i += 2
j = k
k += 1
nums[i] = nums[j]
if n-1-j >= 1:
nums[i+1] = nums[j]
return i+2
return i+1
Problem-solving ideas 【Learning】
double pointer
Link to the original text: [Negative Snow and Bright Candles] Animated solution to help clarify ideas - delete duplicates in an ordered array II - LeetCode
class Solution(object):
def removeDuplicates(self, nums):
slow = 0
for fast in range(len(nums)):
if slow < 2 or nums[fast] != nums[slow - 2]:
nums[slow] = nums[fast]
slow += 1
return slow
作者:fuxuemingzhu
链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/solution/fu-xue-ming-zhu-dong-hua-ti-jie-bang-zhu-yrx5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
After reading the big guy's solution to the problem, it's so far away, I can only be wonderful! Especially in nums[fast] != nums[slow - 2]
this paragraph, if the equality is not true, it means nums[fast]
that the pointed element has not been repeated twice; if the equality is true, it means that nums[fast]
the pointed element has been repeated twice, which subtly replaces the function of counting.