[Leetcode] Majority Element 众数
Majority Element I
Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.
You may assume that the array is non-empty and the majority element always exist in the array.
哈希表法
復雜度
時間 O(N) 空間 O(N)
思路
在遍歷數組的過程中,用一個哈希表記錄每個數出現過的次數,如果該次數大于一半,則說明是眾數。
排序法
復雜度
時間 O(NlogN) 空間 O(1)
思路
將數組排序,這時候數組最中間的數肯定是眾數。
代碼
public class Solution {public int majorityElement(int[] nums) {Arrays.sort(nums);return nums[nums.length / 2];} }位操作法
復雜度
時間 O(N) 空間 O(1)
思路
假設一個數是最多只有32位的二進制數,那么我們從第一位到第32位,對每一位都計算所有數字在這一位上1的個數,如果這一位1的個數大于一半,說明眾數的這一位是1,如果小于一半,說明大多數的這一位是0。
投票法
復雜度
時間 O(N) 空間 O(1)
思路
記錄一個candidate變量,還有一個counter變量,開始遍歷數組。如果新數和candidate一樣,那么counter加上1,否則的話,如果counter不是0,則counter減去1,如果counter已經是0,則將candidate更新為這個新的數。因為每一對不一樣的數都會互相消去,最后留下來的candidate就是眾數。
代碼
public class Solution {public int majorityElement(int[] nums) {int candidate = nums[0], cnt = 0;for(int i = 1; i < nums.length; i++){if(candidate == nums[i]){cnt++;} else if(cnt==0){candidate = nums[i];} else {cnt--;}}return candidate;} }Majority Element II
Given an integer array of size n, find all elements that appear more than ? n/3 ? times. The algorithm should run in linear time and in O(1) space.
投票法
復雜度
時間 O(N) 空間 O(1)
思路
上一題中,超過一半的數只可能有一個,所以我們只要投票出一個數就行了。而這題中,超過n/3的數最多可能有兩個,所以我們要記錄出現最多的兩個數。同樣的兩個candidate和對應的兩個counter,如果遍歷時,某個候選數和到當前數相等,則給相應計數器加1。如果兩個計數器都不為0,則兩個計數器都被抵消掉1。如果某個計數器為0了,則將當前數替換相應的候選數,并將計數器初始化為1。最后我們還要遍歷一遍數組,確定這兩個出現最多的數,是否都是眾數。
代碼
public class Solution {public List<Integer> majorityElement(int[] nums) {List<Integer> res = new ArrayList<Integer>();if(nums.length == 0) return res;int c1 = 1, c2 = 0, n1 = nums[0], n2 = 0;for(int i = 1; i < nums.length; i++){// 如果和某個候選數相等,將其計數器加1if(nums[i] == n1){c1++;} else if(nums[i] == n2){c2++;// 如果都不相等,而且計數器都不為0,則計數器都減1} else if(c1 != 0 && c2 != 0){c1--;c2--;// 如果某個計數器為0,則更新相應的候選數} else {if(c1 == 0){n1 = nums[i];c1 = 1;} else {n2 = nums[i];c2 = 1;}}}c1 = 0;c2 = 0;for(int i = 0; i < nums.length; i++){if(nums[i] == n1) c1++;else if(nums[i] == n2) c2++;}if(c1 > nums.length / 3) res.add(n1);if(c2 > nums.length / 3) res.add(n2);return res;} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的[Leetcode] Majority Element 众数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到自己摔倒掉了好几颗牙齿
- 下一篇: 梦到东西被偷了是什么意思