Majority Element I, II

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.

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




2. Majority Element II

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.

解法來自:http://www.2cto.com/kf/201507/412935.html

    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        int m=-1, n=-1, cm=0, cn=0;//該題解法實際上是在上一題的基礎上略作修改得到的解法
        for(int i=0; i<nums.size(); i++){
            if(m==nums[i]){
                cm++;
            }
            else if(n==nums[i]){
                cn++;
            }
            else if(cm==0){
                cm=1;
                m=nums[i];
            }
            else if(cn==0){
                cn=1;
                n=nums[i];
            }
            else{
                cm--;
                cn--;
            }
        }
        cm=0, cn=0;
        for(auto &it : nums){//注意上題是假設測試用例都包含一個Majority Element,本題沒有這樣的假設
            if(it==m)
                cm++;
            else if(it==n)
                cn++;
        }
        if(cm>(nums.size()/3))
            res.push_back(m);
        if(cn>(nums.size()/3))
            res.push_back(n);
        return res;
    }




發佈了90 篇原創文章 · 獲贊 17 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章