Leetcode-- Majority Elemeny

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.

解題思路:剛開始的想法是直接對已有數組進行排序,但是這樣做會改變原有數組,而且時間複雜度爲O(n*logn)。具體代碼如下:

class Solution {
public:
    int majorityElement(vector<int> &num) {
        sort(num.begin(),num.end());
        return num[num.size()/2];
    }
};
還有一種做法就是遍歷整個數組,設置一個計數器,令第一個元素爲待選元素,當下一元素和待選元素相同時,就++,不同時就--。若計數器爲零,則更換待選元素。具體代碼如下:
class Solution {
public:
    int majorityElement(vector<int> &num) {
        int times = 0;
        int element = 0;
        for(int i=0;i<num.size();++i)
        {
            if(times == 0)
            {
                element = num[i];
                times = 1;
            }
            else
            {
                if(element == num[i])
                    ++times;
                else
                    --times;
            }
        }
        return element;
    }
};



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