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)
  • 相关阅读:
    微信支付
    设计模式
    微信,根据经纬度获取当前城市
    移动端下拉刷新
    angular-seed — AngularJS种子项目
    Send Email
    angularjs 控制器
    ajax 图片上传
    Jpeg-Baseline和Progressive JPEG的区别
    QT启动一个工程
  • 原文地址:https://www.cnblogs.com/yawenw/p/12839021.html
Copyright © 2011-2022 走看看