2017-09-12 LeetCode_169 Majority Element

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Solution:
class Solution {
2
public:
3
    int majorityElement(vector<int>& nums) {
4
        int ans = nums[0], count = 0;
5
        for (int i = 0; i < nums.size(); i++)
6
            if (count == 0) {
7
                ans = nums[i]; count = 1;
8
            } else if (nums[i] == ans) count++;
9
            else count--;
10
        return ans;
11
    }
12
};








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章