Description
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.
Clarification:
Confused why the returned value is an integer, but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
Constraints:
• 1 <= nums.length <= 3 * 104
• -104 <= nums[i] <= 104
• nums is sorted in ascending order.
Example
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3]
Explanation: 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:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3]
Explanation: 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.
Submissions
首先题目要求给定一个排序数组,需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。 不可以使用额外的数组空间,必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
因此解题采用遍历计数的思路,count指相同元素个数,因为本身的原因初始化为1。当元素个数大于2时,删除当前元素并继续遍历。当后一元素与前一元素不同时,重新初始化count,重新计数新元素。最后返回数组长度即可。
同时介绍python删除list中元素的三种方法:
- a.pop(index):删除列表a中index处的值,并且返回这个值.
- del(a[index]):删除列表a中index处的值,无返回值. del中的index可以是切片,所以可以实现批量删除.
- a.remove(value):删除列表a中第一个等于value的值,无返回.
实现代码如下:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
count = 1
idx = 1
while idx < len(nums):
if nums[idx - 1] == nums[idx]:
count += 1
if count > 2:
del nums[idx]
idx = idx - 1
else:
count = 1
idx += 1
return len(nums)