Leetcode 169. Majority Element (Easy) (cpp)

来源:互联网 发布:网络诈骗手段及防范 编辑:程序博客网 时间:2024/05/27 16:41

Leetcode 169. Majority Element (Easy) (cpp)

Tag: Array, Divide and Conquer, Bit Manipulation

Difficulty: Easy


/*169. Majority Element (Easy)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.*/class Solution {public:    int majorityElement(vector<int>& nums) {        if (nums.size() == 1) {            return nums[0];        }        int cnt = 0, majority;        for (int i =0; i < nums.size(); i++) {            if (cnt == 0) {                majority = nums[i];                cnt++;            } else {                majority == nums[i] ? cnt++ : cnt--;                if (cnt > nums.size() / 2) {                    return majority;                }            }        }        return majority;    }};


0 0
原创粉丝点击