zoukankan      html  css  js  c++  java
  • [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
            
            
  • 相关阅读:
    Android 存储 SD卡
    Android 存储 内部存储
    Android 存储 SP存储
    go goroutine
    go 接收命令行参数
    go 文件操作 复制和统计字符
    go 文件操作 判断文件是否存在
    換博客了,新地址https://cutepig123.github.io/
    光盘是个好东西
    俺买过的电子产品
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5366950.html
Copyright © 2011-2022 走看看