首页 > 学院 > 开发设计 > 正文

Majority Element

2019-11-06 07:49:51
字体:
来源:转载
供稿:网友

题目: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.

题解:这道题其实就是计数问题,利用map显然会容易得多。计数后直接进行判断是否满足主要元素的条件。map的find函数的应用在这里使得算法更加简单。

代码如下:

class Solution {public: int majorityElement(vector<int>& nums) { map<int,int>m; for(int i=0;i<nums.size();i++){ map<int,int>::iterator it=m.find(nums[i]); if(it==m.end()){ m[nums[i]]=1; }else{ m[nums[i]]++; } if(m[nums[i]]>(nums.size()/2)){ return nums[i]; } } }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表