题目
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
这个和remove element in list那个是类似的,这里还再次强调了in-place, 所以一定要改变原来给的Nums这个list的元素值,而不是创建新的List,那就必须循环了,这里的constrains是重中之重,
Constraints:
1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums is sorted in non-decreasing order.
所以nums一定不为空,然后Nums值也有范围,最后是有排序的,所以相同的元素必然是一起的。
解法
抛砖引玉一个我的先
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
index = 0
temp = -9999
for i in range(len(nums)):
if nums[i] != temp:
nums[index] = nums[i]
index += 1
temp = nums[i]
return index
这里我用了一个temp值。 实际上有更优化的,就是用第一个值来起始比较就行,然后因为重复是顺序的,那么下一个值总是去比较上一个就行了。
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
j = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
nums[j] = nums[i]
j += 1
return j
当下一个值不等于前一个值得时候,说明不重复的值出现了,要加入目标位置中了。目标位置j标定,每次新的加入后递增。