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)
  • 相关阅读:
    df
    浅谈C#垃圾回收
    eclipse+ADT 进行android应用签名详解
    Android Monkey工具参数意义
    Android Monkey(转载)
    清理Win7右键菜单里“发送到”选项
    Android中LOG机制详解(上)  
    关于微博内容中的短地址ShortURL
    Android中LOG机制详解(下)
    黑盒测试用例设计方法实践(判定表驱动法)
  • 原文地址:https://www.cnblogs.com/yawenw/p/12839021.html
Copyright © 2011-2022 走看看