【LEETCODE】26-Remove Duplicates from Sorted Array

来源:互联网 发布:阿迪达斯网络授权书 编辑:程序博客网 时间:2024/06/01 15:13

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums 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



0 0
原创粉丝点击