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;
}
};