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
            
            
  • 相关阅读:
    git常用命令
    IDEA设置
    redis基础
    SQL 基础
    springboot 配置日志 打印不出来sql
    阿里巴巴开发规范最新版
    rabbitmq用户权限
    rabbitMQ配置文件
    RabbitMQ配置文件(rabbitmq.conf)
    C++模板编程:如何使非通用的模板函数实现声明和定义分离
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5366950.html
Copyright © 2011-2022 走看看