題目: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 in place with constant memory.
leetcode70。 For example,
Given input array 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
?
leetcode-cn,本題在leetcode中屬于esay的級別,也確實不難。
遍歷list,用兩個變量記錄當前位置和下一位置的值,如果兩個值相等,刪掉下一位置元素,不相等就兩個變量均往后移一位。
class Solution(object):def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int"""if len(nums) == 0:return 0elif len(nums) == 1:return 1current = 0next = 1while True:if next >= len(nums):breakif nums[current] == nums[next]:nums.pop(next)else:temp = nextnext = next + 1current = tempreturn len(nums)
?