原题是:
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.
思路是:
不能增加空间,常常就需要考虑通过一次遍历中的两指针的操作,来达到目的。
用i来指着没有重复的部分的尾部,j负责去寻找不同的数,交给i所指着的下一个位置。
不同的元素,去覆盖原有的重复元素就行,不必一定要去删除重复元素。删除思路也是我的第一版问题代码的思路。
代码是:
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i,j = 0,1
if not nums:
return 0
while j < len(nums):
if nums[i] != nums[j]:
nums[i+1] = nums[j]
i += 1
j += 1
else:
j += 1
return i+1
问题代码:
Screen Shot 2017-11-22 at 3.44.06 PM.png因为问题代码用到了list的删除,切片,顺便复习一下:
Screen Shot 2017-11-22 at 3.50.51 PM.png
Screen Shot 2017-11-22 at 4.00.58 PM.png
Screen Shot 2017-11-22 at 4.01.16 PM.png
网友评论