標籤:leetcode majority element java algorithm
題目
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.
相似題目及多數投票演算法
第一眼看到這個題,相信許多人都恩給你聯想到另一個題目:
給定一個整數數組,找出出現次數大於 n/2 的那個數。
如果是找出出現次數大於n/2的數,解決這個問題的思路並不難,可以用Map掃描一遍,並且統計出現次數。但是這種方法的時間複雜度雖然是O(N),空間複雜度也相應的是O(N)。還有一種方法是多數投票演算法,演算法的名字雖然沒聽說過,但是思路相信大多數人還是知道的。
- 如果count==0,則將now的值設定為數組的當前元素,將count賦值為1;
- 反之,如果now和現在數組元素值相同,則count++,反之count–;
- 重複上述兩步,直到掃描完數組。
之前做過的題目都是確定數組中有大於n/2的那個數存在的,所以沒有了後邊的檢查步驟。
思路
看到這題首先想到的是出現次數大於? n/3 ?的數不只有一個,思考了一下,這個數最多有兩個,最少一個也沒有。所以可以用一個大小為2的數組儲存候選結果,最後進行篩選。
然後是候選結果的儲存,考察答題者的知識遷移能力,可憐的是我遷移了半天也沒移對-,-
這裡不說我的錯誤思路了。直接說解題方法吧。
以nums = [8,8,7,7,7]為例
| nums中當前遍曆的數 |
候選數組 |
count數組 |
| 8 |
[8 , 0 ] |
[1 , 0] |
| 8 |
[8 , 0 ] |
[2 , 0] |
| 7 |
[8 , 7 ] |
[2 , 1] |
| 7 |
[8 , 7 ] |
[2 , 2] |
| 7 |
[8 , 7 ] |
[2 , 3] |
一行跟第二行的0是預設初始化的值
代碼
public class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> result = new ArrayList<Integer>(); if(nums == null || nums.length == 0){ return result; } int[] numbers = new int[2]; int[] count = new int[2]; for(int i = 0 ; i < nums.length ; i++){ if(count[0] == 0){ numbers[0] = nums[i]; }else if(count[1] == 0 && numbers[0] != nums[i]){ numbers[1] = nums[i]; } if(numbers[0] == nums[i]){ count[0]++; }else if(numbers[1] == nums[i]){ count[1]++; }else{ count[0]--; count[1]--; } } count[0] = count[1] = 0; for(int i = 0 ; i < nums.length ; i++){ for(int j = 0 ; j < numbers.length ; j++){ if(nums[i] == numbers[j]){ count[j]++; } } } if(count[0] > nums.length / 3) result.add(numbers[0]); if(count[1] > nums.length / 3 && numbers[1] != numbers[0]) result.add(numbers[1]); return result; }}
至於最後這一句
if(count[1] > nums.length / 3 && numbers[1] != numbers[0])
為什麼要判斷numbers[1] != numbers[0],是因為開始的時候初始化為0,要考慮都為0的情況。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
LeetCode--Majority Element II & 多數投票演算法