zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第229题:给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。

    题目:
    给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。  说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
    思路:
    思路1:使用函数;思路2:使用投票法
    程序1:使用函数
    class Solution:
        def majorityElement(self, nums: List[int]) -> List[int]:
            length = len(nums)
            if length <= 0:
                return []
            if length == 1:
                return [nums[0]]
            result = []
            key = length / 3
            for num in set(nums):
                if nums.count(num) > key:
                    result.append(num)
            return result
    程序2:投票法
    class Solution:
        def majorityElement(self, nums: List[int]) -> List[int]:
            length = len(nums)
            if length <= 0:
                return []
            if length == 1:
                return [nums[0]]
            result = []
            key = length // 3
            counter1 = 0
            counter2 = 0
            candidate1 = 0
            candidate2 = 0
            for num in nums:
                if candidate1 == num:
                    counter1 += 1
                elif candidate2 == num:
                    counter2 += 1
                elif counter1 == 0:
                    candidate1 = num
                    counter1 = 1
                elif counter2 == 0:
                    candidate2 = num
                    counter2 = 1
                else:
                    counter1 -= 1
                    counter2 -= 1
            counter1 = 0
            counter2 = 0
            for num_1 in nums:
                if candidate1 == num_1:
                    counter1 += 1
                if candidate2 == num_1:
                    counter2 += 1
            if counter1 > key and candidate1 != candidate2:
                result.append(candidate1)
            if counter2 > key and candidate1 != candidate2:
                result.append(candidate2)
            if counter1 > key and candidate1 == candidate2:
                result.append(candidate1)
            return result
  • 相关阅读:
    Go入门笔记-1 Unbuntu直接安装go 16.5版本
    EdgexGo2.0学习-12 consul不能按服务名获取数据
    EdgexGo2.0学习-11 测试读取ModBus协议
    win10下VirtualBox开启串口
    Linux 开发板通过笔记本上网
    EdgexGo2.0学习-10 edgex-consul 编译 for "-t, --tag" flag: invalid reference format
    EdgexGo2.0学习-9 ERROR: No matching distribution found for PyYAML<4,>=3.10
    EdgexGo2.0学习-8 pip not found
    EdgexGo2.0学习-7 20.10.6: Pulling from library/docker
    EdgexGo2.0学习-6 修改日志时区显示
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12775085.html
Copyright © 2011-2022 走看看