Majority Element

来源:互联网 发布:java动态注入方法 编辑:程序博客网 时间:2024/06/05 09:43
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) {        int res=nums[0];        int times=1;        for(int i=1;i<nums.size();i++)        {            if(nums[i]==res)                ++times;            else                --times;            if(times==0)            {                res=nums[i];                times=1;            }        }        return res;    }};



0 0