LeetCode热题100使用摩尔投票法的题目整理(待更)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode热题100使用摩尔投票法的题目整理(待更)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
多數(shù)元素(simple難度)
https://leetcode-cn.com/problems/majority-element/
與本題相同題目:
劍指offer39. 數(shù)組中出現(xiàn)次數(shù)超過(guò)一半的數(shù)字
本文思路及解法參考了《劍指offer39.數(shù)組中出現(xiàn)次數(shù)超過(guò)一半的數(shù)字》的題解
作者:jyd
鏈接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mian-shi-ti-39-shu-zu-zhong-chu-xian-ci-shu-chao-3/
來(lái)源:力扣(LeetCode)
哈希表法:
class Solution {private Map<Integer, Integer> countNums(int[] nums) {Map<Integer, Integer> counts = new HashMap<Integer, Integer>();for (int num : nums) {if (!counts.containsKey(num)) {counts.put(num, 1);} else {counts.put(num, counts.get(num) + 1);}}return counts;}public int majorityElement(int[] nums) {Map<Integer, Integer> counts = countNums(nums);Map.Entry<Integer, Integer> majorityEntry = null;for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {majorityEntry = entry;}}return majorityEntry.getKey();} }作者:LeetCode-Solution 鏈接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/ 來(lái)源:力扣(LeetCode)排序法:
class Solution {public int majorityElement(int[] nums) {Arrays.sort(nums);return nums[nums.length / 2];} }作者:LeetCode-Solution 鏈接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/ 來(lái)源:力扣(LeetCode)?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的LeetCode热题100使用摩尔投票法的题目整理(待更)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: oracle存储过程无效字符_ORA-2
- 下一篇: 线性独立成分分析(ICA)与鸡尾酒会问题