leetcode: 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:当天 today sql 编辑:程序博客网 时间:2024/05/20 11:35

Q

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

AC

class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        i = 0        for n in nums:            if i < 2 or n > nums[i-2]:                nums[i] = n                i += 1        return i# Time:  O(n)# Space: O(1)class Solution2(object):    def removeDuplicates(self, A):        if not A:            return 0        last, i, same = 0, 1, False        while i < len(A):            if A[last] != A[i] or not same:                same = A[last] == A[i]                last += 1                A[last] = A[i]            i += 1        return last + 1if __name__ == "__main__":    assert Solution().removeDuplicates([1, 1, 1, 2, 2, 3]) == 5


阅读全文
0 0
原创粉丝点击