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)
  • 相关阅读:
    Alone
    vue父组件中调用子组件的方法
    常用CSS的布局问题;
    Flex语法和常用鼠标手势
    如何解决浮动元素高度塌陷---CSS
    Vue中使用 iview 之-踩坑日记
    路由懒加载---Vue Router
    <input type="file">如何实现自定义样式
    sticky -- position定位属性sticky值之粘性定位;
    Vue组件传值(三)之 深层嵌套组件传值
  • 原文地址:https://www.cnblogs.com/yawenw/p/12839021.html
Copyright © 2011-2022 走看看