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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

主元素问题 Majority Element

發(fā)布時間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 主元素问题 Majority Element 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2018-09-23 13:25:40

主元素問題是一個非常經(jīng)典的問題,一般來說,主元素問題指的是數(shù)組中元素個數(shù)大于一半的數(shù)字,顯然這個問題可以通過遍歷計數(shù)解決,時間復雜度為O(n),空間復雜度為O(n)。這樣的算法有兩個弊端,一是空間復雜度較高,二是沒法處理數(shù)據(jù)流問題。

因此就有了Boyer-Moore Majority Vote algorithm,這個算法可以用來高效的解決主元素問題,并且空間復雜度降到了O(1),時間復雜度保持不變。

算法的思路就是將不同的元素進行抵消,最后剩余的就是最終的結(jié)果。

如果說題目中沒有明確說明一定存在主元素,那么還需要額外一次遍歷來確認當前的解為主元素。

一、主元素問題

問題描述:

問題求解:

    public int majorityElement(int[] nums) {int candidate = 0;int count = 0;for (int i = 0; i < nums.length; i++) {if (nums[i] == candidate) count++;else if (count == 0) {candidate = nums[i];count = 1;}else count--;}return candidate;}

?

二、Follow Up

問題描述:

問題求解:

    public List<Integer> majorityElement(int[] nums) {if (nums == null || nums.length == 0) return new ArrayList<>();int candidate1 = 0;int candidate2 = 0;int count1 = 0;int count2 = 0;for (int i = 0; i < nums.length; i++) {if (nums[i] == candidate1) count1++;else if (nums[i] == candidate2) count2++;else if (count1 == 0) {candidate1 = nums[i];count1 = 1;}else if (count2 == 0) {candidate2 = nums[i];count2 = 1;}else {count1--;count2--;}}List<Integer> res = new ArrayList<>();count1 = 0;count2 = 0;for (int i = 0; i < nums.length; i++) {if (nums[i] == candidate1) count1++;else if (nums[i] == candidate2) count2++;}if (count1 > nums.length / 3) res.add(candidate1);if (count2 > nums.length / 3) res.add(candidate2);return res;}

?

轉(zhuǎn)載于:https://www.cnblogs.com/TIMHY/p/9692531.html

總結(jié)

以上是生活随笔為你收集整理的主元素问题 Majority Element的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。