leetcode169. 求衆數(map的用法、摩爾投票法)

題目描述:ios

給定一個大小爲 的數組,找到其中的衆數。衆數是指在數組中出現次數大於 ⌊ n/2 ⌋ 的元素。數組

你能夠假設數組是非空的,而且給定的數組老是存在衆數。spa

示例:code

輸入:[2, 2, 1, 1, 1, 2, 2]blog

輸出:2排序

方法一:創建map來記錄數組中每一個不重複元素的出現次數,而後遍歷map,查找map中value大於n/2的key值,該值即爲衆數。ci

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;

class Solution{
public:
    int majorityElement(vector<int>& nums){
        map<int, int> mapElement;   //初始化一個map,其中key表示數組中不重複的元素,value表示該元素在數組中出現的次數 
        int element;
        for(int i=0; i<nums.size();++i){
            if(mapElement.count(nums[i]) == 0) //查找map中是否包含該元素,若爲0,則不包含 
                mapElement.insert(make_pair(nums[i], 1));
            else
                mapElement[nums[i]] += 1;    
        }
        map<int, int>::iterator it = mapElement.begin();
        while(it != mapElement.end()){
            if(it->second > nums.size()/2){
                element = it->first;
                break;
            }
            it++;
        }
        return element; 
    }
};

int main(){
    Solution solution;
    vector<int> vec;
    int i;
    do{
        cin>>i;
        vec.push_back(i);
    }while(getchar() != '\n');
    int res;
    res = solution.majorityElement(vec);
    cout<<res<<endl;
    return 0;
}

 

方法二:因爲數組中衆數必定是數組中出現次數大於n/2的元素,因此咱們將數組排序後,位於數組中間的那個元素必定是衆數。element

class Solution{
public:
    int majorityElement(vector<int>& nums){
        sort(nums.begin(), nums.end());
        int element = nums[nums.size()/2];
        return element;
    }
}; 

方法三:因爲衆數是出現次數大於n/2的元素,設置數組中第一個元素爲衆數,count爲1。從第二個元素開始遍歷數組,若元素與衆數相等,則count+1,若不等,則count-1。當count變爲0時,咱們更新衆數爲下一個元素,count從新置爲1.數組遍歷完成獲得的衆數即爲所求衆數。get

上述方法又稱爲摩爾投票法,即查找輸入中重複出現超過一半以上(n/2)的元素。摩爾投票的思想:在每一輪投票過程當中,從數組中找出一對不一樣的元素,將其從數組中刪除,這樣不斷的刪除直到沒法再進行投票,若是數組爲空,則沒有任何元素出現的次數超過該數組的一半。若是隻存在一種元素,則這個元素即爲目標元素。it

class Solution{
public:
    int majorityElement(vector<int>& nums){
        int element = nums[0];
        int count = 1;
        for(int i=1; i<nums.size(); ++i){
            if(nums[i] == element)
                count++;
            else
                count--;
            if(count == 0){
                element = nums[++i];
                count++;
            }
        }
        return element;
    }
};
相關文章
相關標籤/搜索