1. 程式人生 > >Majority Number 解題報告

Majority Number 解題報告

Majority Number

Description

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

It should support push, pop and min operation all in O(1) cost.

Notice

You may assume that the array is non-empty and the majority number always exist in the array.

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

實現思路

這道題基於投票演算法,
我們先假設陣列nums中第一個數nums[0]就是我們要找的數vote,同時維護一個count變數,在後面判斷中,如果nums[i] == vote(i=1….nums.length-1),則count++,如果不等,分兩種情況:
1. 如果count > 0,則count–
2. 如果count = 0,則更新vote = nums[i]
為什麼這樣能得到我們要求的數major?我們可以這樣分析:
對於任意一個數組nums中不等於major的數,基於我們的演算法,它最終一定會被替換。因為它們的count(不超過一半)必定會在major(count大於一半)的不等判斷下,被替換
那major會不會被替換呢?可能中間過程會,但遍歷到最後,留下的必定是major。
根據此思路,求解方法如下:

java實現

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        // write your code
        int vote = nums.get(0);
        int count = 1;
        for(int i = 1 ; i < nums.size(); i ++){
            if
(nums.get(i) == vote){ count ++; }else if(count == 0){ vote = nums.get(i); }else{ count --; } } return vote; } }

python實現

class Solution:
    """
    @param nums: A list of integers
    @return: The majority number
    """
    def majorityNumber(self, nums):
        # write your code here
        if not nums:
            return None
        vote = nums[0]
        count = 0
        for num in nums:
            if num == vote:
                count += 1
            elif count == 0:
                vote = num
            else:
                count -= 1
        return vote