zoukankan      html  css  js  c++  java
  • LeetCode:229. 求众数 II

    1、题目描述

    给定一个大小为 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

    说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。

    示例 1:

    输入: [3,2,3]
    输出: [3]
    

    示例 2:

    输入: [1,1,1,3,3,2,2,2]
    输出: [1,2]
    

    2、题解

    2.1、解法一

    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            n = len(nums)
            m = n//3
            dic = {}
    
            i = 0
            while i <n:
                k = nums[i]
                if k not in dic:
                    dic[k] = 1
                else:
                    print(k)
                    dic[k] = dic[k] +1
                i += 1
    
            print(m)
            print(dic)
            return [i for i in dic if dic[i] >m]
    

    2.2、解法二

    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            n = len(nums)
            m = n//3
            nums.sort()
            i = 0
            ret = []
            while i <n:
                tmp = nums[i]
                count = 0
                while i < n and nums[i] == tmp:
                    count += 1
                    i += 1
                if count > m:
                    ret.append(tmp)
                if count == 0:
                    i = i+1
            return ret
    

      

  • 相关阅读:
    向 DataGridView 的行集合中添加行
    添加form窗口最大化最小化事件
    转义字符表
    键盘输入变简单了
    数字9X9的表格
    统计你输入的任意字符
    一个九九表
    用冒泡法排序
    学生会
    任意排序几个数
  • 原文地址:https://www.cnblogs.com/bad-robot/p/10066297.html
Copyright © 2011-2022 走看看