美文网首页
每天(?)一道LeetCode(2) Remove Duplic

每天(?)一道LeetCode(2) Remove Duplic

作者: 失业生1981 | 来源:发表于2019-01-16 23:27 被阅读0次

Array

26. Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
不是很理解:
不能为另外一个数组分配额外的空间,必须使用常量内存完成。

Solutions

利用两个指针

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        j = 0
        i = 1
        while i<len(nums):
            if nums[j] == nums[i]:
                i +=1
            else:
                j+=1
                nums[j] = nums[i]
        del nums[j+1:]
        return len(nums)

下面这个算法有点儿没看明白,明天再看下

    def removeDuplicates1(self, A):
        if not A:
            return 0

        last = 0
        for i in range(len(A)):
            if A[last] != A[i]:
                last += 1
                A[last] = A[i]
        return last + 1

相关文章

网友评论

      本文标题:每天(?)一道LeetCode(2) Remove Duplic

      本文链接:https://www.haomeiwen.com/subject/hngvdqtx.html