Leetcode-Remove-Duplicates-from-Sorted-Array

Leetcode 26. Remove Duplicates from Sorted Array 解題心得

題目: 26. Remove Duplicates from Sorted Array

題目描述

給定一組已排序的整數陣列 nums,請移除陣列中所有重複的元素,並且回傳移除後的陣列長度。
同時不可以使用額外的陣列空間,必須在原地操作陣列,需要考慮到陣列的順序。

大概像這樣:

1
2
3
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
return nums = [1,2,_]

解題思路

python 的話,可以用 set 來過濾掉重複的元素,再把 set 後的結果指派給 nums
然後再sort一次,就可以得到答案了。

Code

1
2
3
4
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
nums[:] = sorted(set(nums))
return len(nums)

Runtime 76 ms Beats 94.12%

Memory 17.4 MB Beats 99.93%


Leetcode-Remove-Duplicates-from-Sorted-Array
https://hibana2077.github.io/post/Leetcode-Remove-Duplicates-from-Sorted-Array.html
Author
hibana2077
Posted on
September 18, 2023
Licensed under