您的位置:首页 > 其它

leetcode刷题,总结,记录,备忘 169

2015-06-21 23:47 387 查看
leetcode169Majority 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.

这个题目很简单,,,排序一下,遍历统计一下最出现次数最多,保存下来,即可。
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int maxv = nums[0], maxvc = nums[0], maxc = 0, count = 0;
        for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)
        {
            if (maxvc != *it)
            {
                if (count > maxc)
                {
                    maxv = maxvc;
                    maxc = count;
                }
                maxvc = *it;
                count = 0;
            }
            count++;
        }
    	if (count > maxc)
	    {
    		maxv = maxvc;
    		maxc = count;
	    }
        
        return maxv;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: