日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode热题100使用摩尔投票法的题目整理(待更)

發布時間:2023/12/16 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode热题100使用摩尔投票法的题目整理(待更) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

多數元素(simple難度)

https://leetcode-cn.com/problems/majority-element/

與本題相同題目:

劍指offer39. 數組中出現次數超過一半的數字

本文思路及解法參考了《劍指offer39.數組中出現次數超過一半的數字》的題解
作者: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/
來源:力扣(LeetCode)

class Solution {public int majorityElement(int[] nums) {int x = 0, votes = 0;for(int num : nums){if(votes == 0) x = num;votes += num == x ? 1 : -1;}return x;} }作者: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/ 來源:力扣(LeetCode)

class Solution {public int majorityElement(int[] nums) {int x = 0, votes = 0, count = 0;for(int num : nums){if(votes == 0) x = num;votes += num == x ? 1 : -1;}// 驗證 x 是否為眾數for(int num : nums)if(num == x) count++;return count > nums.length / 2 ? x : 0; // 當無眾數時返回 0} }作者: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/ 來源:力扣(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/ 來源:力扣(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/ 來源:力扣(LeetCode)

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的LeetCode热题100使用摩尔投票法的题目整理(待更)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。