zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge6 之 投票算法

    语法:

       JAVA遍历map:for(Map.Entry<Integer, Integer> entry : map.entrySet())

       Python max函数: max(counts.keys(), key=counts.get), 其中counts.keys()是对象,key后面是函数。

    本题介绍两种解法:

    1.boyer moore投票算法:申请变量candidate 和 变量count初始化为0,遍历数组num,如果count=0,candidate=num,count += (candidate==num)?1:-1

    2.HashMap:用hashmap统计元素及元素出现的次数,返回 the majority num。

    JAVA

    class Solution {
        public int majorityElement(int[] nums) {
            int count = 0;
            Integer candidate = null;
            for(int num: nums){
                if(count == 0) candidate = num;
                count += (candidate == num) ? 1 : -1;
            }
            return candidate;
        }
    }
    class Solution {
        public int majorityElement(int[] nums) {
            Map<Integer, Integer> map = new HashMap<>();
            for(int num : nums){
                map.put(num, map.getOrDefault(num, 0)+1);
            }
            Map.Entry<Integer, Integer> majorityEntry = null;
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
                if(majorityEntry == null || entry.getValue() > majorityEntry.getValue()){
                    majorityEntry = entry;
                }
            }
            return majorityEntry.getKey();
        }
    }

    Python3

    class Solution:
        def majorityElement(self, nums: List[int]) -> int:
            count = 0
            candidate = None
            for num in nums:
                if count == 0:
                    candidate = num
                count += 1 if candidate == num else -1
            return candidate
    class Solution:
        def majorityElement(self, nums: List[int]) -> int:
            d = collections.Counter(nums)
            res = 0
            temp = 0
            for key, val in d.items():
                if val > temp:
                    temp = val
                    res = key
            return res
            #return max(counts.keys(), key=counts.get)
  • 相关阅读:
    census 安全处理模式
    基于squid 暴露k8s 服务
    nginx 动态模块问题
    juicefs 多s3 bucket 使用
    k8s 数据卷需要很长时间才能挂载成功
    一种基于s3 管理haproxy 配置的模式
    WebSub 互联网分布式\订阅标准
    maven 多模块父模块问题deploy 问题
    nginx 作为s3 的gateway
    juicefs 单机试用
  • 原文地址:https://www.cnblogs.com/yawenw/p/12839021.html
Copyright © 2011-2022 走看看