Majority Element

来源:互联网 发布:美国就业率数据2017 编辑:程序博客网 时间:2024/05/17 09:03

LeetCode题目来源

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.

这道题我的方法是先将数组进行排序,然后从第一个数开始进行比较,往后记录每次相同的数的个数,如果遇到不同的就重置,直到遇到相同的数出现了⌊ n/2 ⌋ 次,代码如下:

class Solution {public:    int majorityElement(vector<int>& nums) {        sort(nums.begin(),nums.end());        int Maxnum = nums[0];        int Maxcount = 0;        int curNum = nums[0];        for(int i = 0 ; i < nums.size(); i++){            if(nums[i] == curNum ){                Maxcount++;                if(Maxcount > nums.size()/2){                    return nums[i];                }            }            else{                Maxcount = 1;                curNum = nums[i];            }        }    }};
0 0