- Leetcode-26Remove Duplicates fro
- LeetCode 26. Remove Duplicates f
- ZXAlgorithm - Leetcode Top Inter
- Remove Duplicates from Sorted Ar
- 26 Remove Duplicates From Sorted
- 83 Remove Duplicates From Sorted
- Remove Duplicates from Sorted Ar
- Remove Duplicates from Sorted Ar
- Remove Duplicates from Sorted Ar
- Remove Duplicates from Sorted Ar
删除排序数组中的重复项
英文原文
Given a sorted array nums, 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 by modifying the input array in-place with o(1) extra memory.
Example 1:
Given 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 returned length
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4]
Your function should return length = 5, with the first five elements of nums being modified to 0,1,2,3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
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 modification to the input array will be known to the caller as well.
Internally you can think of this:
// num is passed in by reference. (i.e, without making a copy)
int len = removeDuplicates(nums)
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]);
}
词汇提醒:
- In-place 原地
- Passed in 引用
中文
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
题解
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
temp_dict = {}
temp_list = []
for index, i in enumerate(nums):
if not temp_dict.get(i):
temp_dict[i] = True
else:
temp_list.append(index)
tag = 0
for i in temp_list:
del nums[i - tag]
tag += 1
return len(nums)
- 注在遍历列表的时候不应该对列表有增删操作(index会随列表的长度变化而变化)
网友评论