Leetcode #169 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 majorNum = nums.at(0);
	int countOfMN = 1;
	for (int i = 1; i < nums.size(); ++i)
	{
		if (!countOfMN)
		{
			majorNum = nums.at(i);
			countOfMN = 1;
		}
		else if (majorNum == nums.at(i))
		{
			++countOfMN;
		}
		else --countOfMN;//majorNum != nums.at(i)
	}
	return majorNum;
}

 思路比較簡單:只要按順序找數列,兩個兩個地取出來,只要是不一樣的數,就對消掉。如果相同,就保留下來並記錄個數,最後剩下的就是主元素。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章