题目:
Given a sorted array, 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:
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 new length.
solution:
题目只说了让返回新数组的长度,空间复杂度为O(1),所以不需要考虑新数组的值和顺序以及丢弃了哪些数值
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
length = len(nums)
newlength = 0
#空间复杂度为O(1)所以不能考虑使用新数组,考虑两个指针也就是两个值比较大小,如果不相等,长度加一,否则不变
#从下标为1开始比较,首先要注意判断如果length<1时,应该return 0,否则会报错;
#依次比较,如果与前一个不相等,则nums[newlength] != nums[i],将nums[newlength] = nums[i],并将长度加一,否则进行下一个的比较for i in range(1,length):
if nums[i] != nums[newlength]:
newlength = newlength + 1
nums[newlength] = nums[i]
return newlength+1