LeetCode--Majority Element II & 多數投票演算法

來源:互聯網
上載者:User

標籤: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)。還有一種方法是多數投票演算法,演算法的名字雖然沒聽說過,但是思路相信大多數人還是知道的。

  1. 如果count==0,則將now的值設定為數組的當前元素,將count賦值為1;
  2. 反之,如果now和現在數組元素值相同,則count++,反之count–;
  3. 重複上述兩步,直到掃描完數組。

之前做過的題目都是確定數組中有大於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 & 多數投票演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.