leetcode學習篇四——Majority Element

題目如下:
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.
難度:easy 通過率:43.7%

一開始看到題目,頭腦發熱,就直接寫了一個分支法求最大值,然後才發現自己理解錯題目了,是找出現次數大於數組大小一半的元素,所以可以確定這樣的元素只有一個,於是就直接採用暴力解法,兩次循環,時間複雜度O(n^2),代碼如下,果真超時了……

int majorityElement(vector<int>& nums) {
    if(nums.size() == 1) return nums[0];
    for(int i = 0; i < nums.size(); i++) {
        int count = 0;
        for(int j = 0; j < nums.size(); j++) {
            if(nums[j] == nums[i]) {
                count ++;
            }
            if(count > nums.size()/2) {
                return nums[i];
            }
        }
    }
}

同樣的思路,也是將每個數的數量計算出來,然後判斷當數量大於數組大小一半時便返回,而考慮到以上做法對每個數都從頭到尾計算數量,導致超時,所以考慮使用map在一次遍歷中將每個數的數量記錄下來,代碼如下,因爲find函數是通過二叉樹實現,所以以下代碼時間複雜度爲O(nlogn).

class Solution {
public:
    int majorityElement(vector<int> &nums) {
        map<int, int> res;
        int result;
        for(int i = 0; i < nums.size(); i++) {
            map<int, int>::iterator it = res.find(nums[i]);
            if(it == res.end()) res[nums[i]] = 1;
            else res[nums[i]] ++;
            if(res[nums[i]] > nums.size() / 2) {
                return nums[i];
            } 
        }
        return 0;
    }
};

看了一下leetcode上面的討論,通過Moore voting algorithm解決了這個問題,算法演示鏈接:點擊此處
算法基本思想:每次在數組中找出一對不同的元素然後刪除,因爲Majority Element的次數大於一半,所以肯定最後剩下該元素,
算法複雜度:O(n),代碼實現如下,

int majorityElement(vector<int> &nums) {
    int count = 0, result;
    for(int i = 0; i < nums.size(); i++) {
        if(count == 0) result = nums[i];
        if(result == nums[i]) count ++;
        else count--;
    }
    return result;
}
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章