给定一个已经排好序的数组,原位去重,并返回去重后数组的长度。问题的要求是不能用数组的copy,也就是空间复杂度为 O ( 1 ) O(1) O(1)。
比如:[0,0,1,1,2]
原位去重后的数组的前3个数分别是0,1,2,返回的长度为3。
思路:
难点再于in-place,但是解题的出发点也在in-place,既然是原位。如上面的例子,一个长度是5的数组,去重的前三个位置放0,1,2,那么其它数去哪儿了,所以只能是来交换或赋值。
关键是定义两个指针,一个是要求的已经去重的数组的指针,另一个是原来的数组遍历时的指针。
实现中,把交换优化为了赋值。
先画一下:
# -*- coding: utf-8 -*-
from typing import List
def removeDuplicate(nums: List[int]) -> int:
"""
remove duplicate num of a sorted array in-place which is passed in, and return the new
length of array
:param nums:
:return:
"""
target_idx = 0
remove_idx = 1
for i in range(len(nums)):
if remove_idx == len(nums):
break
if nums[remove_idx] > nums[target_idx]:
nums[target_idx + 1], nums[remove_idx] = nums[remove_idx], nums[target_idx + 1]
target_idx += 1
remove_idx += 1
else:
remove_idx += 1
return target_idx + 1
def removeDuplicate2(nums: List[int]) -> int:
"""
remove duplicate num of a sorted array in-place which is passed in, and return the new
length of array
:param nums:
:return:
"""
target_idx = 0
remove_idx = 1
for i in range(len(nums)):
if remove_idx == len(nums):
break
if nums[remove_idx] > nums[target_idx]:
# 把交换优化为赋值
nums[target_idx + 1] = nums[remove_idx]
target_idx += 1
remove_idx += 1
else:
remove_idx += 1
return target_idx + 1
def removeDuplicate3(nums: List[int]) -> int:
"""
remove duplicate num of a sorted array in-place which is passed in, and return the new
length of array
:param nums:
:return:
"""
# 优化了两个指针的写法,用j直接作为要比较的指针,另外定义一个指针
i = 0
for j in range(1, len(nums)):
if nums[j] > nums[i]:
nums[i + 1] = nums[j]
i += 1
return i + 1
if __name__ == '__main__':
l = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
# [0,1,0,1,1, 2,2,3,3,4]
# [0,1,2,3,4,0,1,2,3]
print(removeDuplicate2(l))
print(l)