169. Majority Element (C++)

题目:

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.

解答:

//169
//这个题思路还是比较清晰的,如果这个值有绝对的数量优势,那么它就可以和别的值进行抵消
//遇到相同值计数加一,遇到不同值计数减一,当计数器变为零时,主值转变为遇到的值
int majorityElement(vector<int>& nums) {
    int key = nums[0], n = 1;
    for (int i = 1; i < nums.size(); i++)
    {
        n == 0 ? (n++, key = nums[i]) : (key == nums[i] ? n++ : n--);
    }
    return key;
}//(16ms)

你可能感兴趣的:(LeetCode)