Majority Element
2015-11-05 21:32
281 查看
题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
分析:
上来就想到利用map
另一种思路,好像比我的慢
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
class Solution { public: int majorityElement(vector<int>& nums) { size_t m = nums.size() / 2; map<int,int> nums_count; vector<int>::iterator it = nums.begin(); while(it != nums.end()) nums_count[*it++]++; map<int,int>::iterator it2 = nums_count.begin(); while(it2 != nums_count.end()) { if( it2->second > m) return it2->first; it2++; } } };
另一种思路,好像比我的慢
int majorityElement1(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size()/2]; }
相关文章推荐
- 冒泡排序语法树
- 全球参考系统(WRS)概述及常用工具汇总
- Linux常用命令大全
- 第四届山东省网络安全技能大赛 write up
- Linux命令——find
- Python中的装饰器decorator
- “互联网+”创新创业计划书(一)
- 软件测试相关的生命周期总结
- Openstack计算节点宕机迁移方案
- LeetCode—137 Single Number II
- js正则表达式
- 每个程序员都会的 35 个 jQuery 小技巧
- 调用 C 动态库
- Android状态栏提醒——Notification
- 词法分析器
- swf文件解析(二) 文件分解及Tag获取
- hdoj 2191悼念512汶川大地震遇难同胞——珍惜现在,感恩生活【dp】
- 二叉搜索树与双向链表
- map写数据到本地磁盘过程解析----spill和merge
- 冒泡排序文法