26. Remove Duplicates from Sorted Array-Python

来源:互联网 发布:zabbix snmp 端口号 编辑:程序博客网 时间:2024/06/06 05:58

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.

思路

  1. 设置两个游标ij分别指向每个元素的索引,和不等元素的索引,初始值都指向index=0的元素;
  2. 遍历list,若后一个元素等于前一个元素且后一个元素未越界,则i加1,直到找到不相等或越界;
  3. 如果未越界,且i不等于j,则将nums[i]移到位置j处;
  4. ij分别加1(不管此时ijj1),直到i小于n时退出循环。

Code

class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        #this quesion asserts the nums is sorted        i=0 #index for nums        j=0 #index for different elements        n=len(nums)        while i<n:            while i<n-1 and nums[i+1]==nums[i]:                i+=1            # if i<n-1 running here indicates we find nums[i] is inequal to nums[i+1]            if i<n and i!=j:                nums[j]=nums[i]            j+=1            i+=1        return j
原创粉丝点击