您的位置:首页 > 其它

【LEETCODE】26-Remove Duplicates from Sorted Array

2015-12-16 23:26 627 查看
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.
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.

参考: http://m.blog.csdn.net/blog/xiaolewennofollow/45168279


题意:
一个有序数组,保持顺序挑出无重复的数字放在数组前段,返回新的长度
思路:
i向前移动,一遇到与keyvalue不同的值就:keyvalue更新,位置start与i上的值交换,start向前移动一位
start相当于新的无重复数组的终点

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

if nums==[]:
return 0
n=len(nums)
keyvalue=nums[0]
start=1

for i in range(n):
if nums[i]!=keyvalue:
keyvalue=nums[i]
nums[start]=nums[i]
start+=1

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