[LeetCode]169.Majority Element,majorityelement

來源:互聯網
上載者:User

[LeetCode]169.Majority Element,majorityelement
【題目】

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.

【分析】

思路是計算數組前一半出現元素的頻率,如果數目大於⌊ n/2 ⌋就返回

【代碼】

/**********************************   日期:2015-01-30*   作者:SJF0115*   題目: 169.Majority Element*   網址:https://oj.leetcode.com/problems/majority-element/*   結果:AC*   來源:LeetCode*   部落格:**********************************/#include <iostream>#include <vector>using namespace std;class Solution {public:    int majorityElement(vector<int> &num){        int len = num.size();        int size = len / 2 + 1;        int count;        // 統計前一半的元素個數        for(int i = 0;i < size;++i){            // 跳過重複元素            while(i > 0 && num[i] == num[i-1]){                ++i;            }//while            count = 0;            for(int j = i;j < len;++j){                if(num[j] == num[i]){                    ++count;                    if(count >= (len+1)/2){                        return num[i];                    }//if                }//if            }//for        }//for    }};int main(){    Solution solution;    vector<int> num = {8,8,7,7,7};    int result = solution.majorityElement(num);    // 輸出    cout<<result<<endl;    return 0;}


【分析二】

Every number in the vector votes for itself, the majority number gets the most votes. Different number offsets the votes.

遇到不同的就相互抵銷,遇到相同的就增加,當count = 0時,重新開始

【代碼二】

class Solution {public:    int majorityElement(vector<int> &num){        int vote = num[0];        int count = 1;        int size = num.size();        //vote from the second number        for(int i = 1;i < size;++i){            if(count == 0){                vote = num[i];                count++;            }//if            else if(vote == num[i]){                count++;            }            else{                count--;            }        }//for        return vote;    }};

【分析】

Majority Element肯定佔據至少一半的元素,因此排序後中間元素一定是Majority Element

【代碼】

class Solution {public:    int majorityElement(vector<int> &num){        int size = num.size();        // 只有一個元素        if(size == 1){            return num[0];        }//if        sort(num.begin(),num.end());        return num[size / 2];    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.