您的位置:首页 > 编程语言 > Python开发

LeetCode 80 Remove Duplicates from Sorted Array II (Python详解及实现)

2017-08-08 16:24 225 查看
【题目】

Follow up for "RemoveDuplicates":

What if duplicates are allowed at mosttwice?

 

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 matterwhat you leave beyond the new length.

 

给定一个数组,数组中的数字最多允许出现两次,若大于两次则保留两个该数字,最后返回数组长度

 

【思路】

定义一个标志位exist,为True则表明该数字已经出现两次,定义一个指针pstart,指示当前数组有效位置。

 

 

【Python实现】

# -*- coding: utf-8 -*-

"""

Created on Tue Aug  8 15:32:54 2017

 

@author: Administrator

"""

 

class Solution(object):

   def removeDuplicates(self, nums):

       """

       :type nums: List[int]

       :rtype: int

       """

       size = len(nums)

       if size == 0 or size == 1:

           return size

       pstart = 1

       i = 1

       tmp = nums[0]4

       exist = False

       while i < size:

           if nums[i] == tmp:

                if not exist:#未检测到两个相同数字

                    nums[pstart] = tmp

                    pstart += 1

                    exist =True

           else:#不相同的情况

                tmp = nums[i] #更新tmp

                exist = False

                nums[pstart] = tmp#用当前数字替换pstart所在位置的数

                pstart += 1

           i += 1

       print(nums[:pstart])

       return pstart

 

 

if __name__ == '__main__':

    nums = [1,1,1,2,2,3,4,4,4,5]

    S = Solution()

    S.removeDuplicates(nums)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Python