LeetCode Remove Duplicates from Sorted Array

BabbleDay posted @ 2015年7月17日 00:14 in 刷题防身 with tags python leetcode Remove Duplicates from Sorted , 422 阅读

使用del删除list里的元素

 

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def removeDuplicates(self, nums):
        i, j = 0, 1
        if len(nums)<2:
            return len(nums)
        while(i < len(nums)-1):
            j = i+1
            if nums[i] == nums[j]:
                del nums[j]
            else:
                i += 1
        return len(nums)

 

不改变list

 

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def removeDuplicates(self, nums):
        l, i = 1, 1
        if len(nums)<2:
            return len(nums)
        for i in range(1,len(nums)):
            if nums[i]!=nums[i-1]:
                nums[l] = nums[i]
                l += 1
        return l

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter