[LeetCode]题解(python):80-Remove Duplicates from Sorted Array II

题目来源


https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

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 1122 and 3. It doesn't matter what you leave beyond the new length.


题意分析


Input: type numsList[int]; 

Output: rtype int;

Conditions:删除array中的重复元素,但是允许重复次数为2,保证返回的length长度下包含所需值,大于length长度的元素不考虑


题目思路

穷举思路,只要出现过两次,就将该元素忽略。其实因为数组是有序的,穷举效率肯定差一点,但是leetcode OJ通过了= =


AC代码(Python)

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        k = 0
        l = len(nums)
        if l == 0:
            return 0
        for i in range(l):
            t = 0;
            for j in range(k):
                if nums[i] == nums[j]:
                    t+=1
            if t < 2:
                nums[k] = nums[i]
                k += 1
        #for i in range(k):
        #    print(str(nums[i]) + " ")
        return k
        
        

 

posted @ 2016-04-08 10:27  loadofleaf  Views(222)  Comments(0Edit  收藏  举报