Problem
Inspired from problem 26 and 80 from leetcode, problem has been changed to be as follow:
Given a sorted array nums, remove the duplicates in-place such that each element appear only max_appear_time 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.
Solution
This problem is related to the topic of array and two pointers.
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int], max_appear_time: int) -> int:
"""
Inspired from discussion
Refer to 26. Remove Duplicates from Sorted Array
"""
if not nums:
return
i = 0
# flag = False
# max_appear_time = 1
appear_time = 1
for j in range(1, lBackspace String Compareen(nums)):
if nums[i] == nums[j]:
if appear_time != max_appear_time:
# flag = True
appear_time += 1
i += 1
nums[i], nums[j] = nums[j], nums[i]
else:
appear_time = 1
# flag = False
i += 1
nums[i], nums[j] = nums[j], nums[i]
return i + 1
Methond of two pointer is used in this problems. Similar problems using two pointer methods are:
- 283 move zeros
- 27 remove element