您的位置:首页 > 编程语言 > Python开发

[LeetCode]Remove Duplicates from Sorted Array@python

2018-01-21 15:36 519 查看
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 arrayin-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.

没什么难度,遍历一下,把上一次结果存到中间值中,对比,不同就计数加一

class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0

j = 0
for i in range(1,len(nums)):
if nums[i] != nums[j]:
j += 1
nums[j] = nums[i]

return j+1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode