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)

 

posted @ 2020-05-06 21:29  yawenw  阅读(241)  评论(0编辑  收藏  举报