https://leetcode.com/problems/remove-duplicates-from-sorted-array/
思路简单。但是要找对循环点。removeDuplicates2中用j scan所有元素才是最佳方案。 ref: http://www.cnblogs.com/zuoyuan/p/3779816.html
class Solution(object):
def removeDuplicates2(self, nums):
if len(nums) == 0:
return 0
i = 0
for j in range(0, len(nums)):# let j scan all the elements
if nums[j] != nums[i]:
nums[j], nums[i+1] = nums[i+1], nums[j]
i += 1
return i+1
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
if len(nums) == 1:
return 1
i,j = 0,0
while j < len(nums):# j == len(nums) is the stop condition
while j < len(nums) and nums[j] == nums[i]:
j += 1
if j < len(nums):
nums[i+1] = nums[j]
i += 1
return len(nums[:i + 1])