leetcode刷题日记——Majority Element
2015-12-17 19:57
155 查看
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 ⌋ 的元素,这类问题比较简单,使用一个map对里面的元素计数既可以,然后比较每个元素出现的次数是否大于n/2.
实现代码如下:
You may assume that the array is non-empty and the majority element always exist in the array.
问题分析:题目的目标就是找出整数数组中出现的次数大于⌊ n/2 ⌋ 的元素,这类问题比较简单,使用一个map对里面的元素计数既可以,然后比较每个元素出现的次数是否大于n/2.
实现代码如下:
class Solution { public: int majorityElement(vector<int>& nums) { map<int,int> count; int n=nums.size(); int majority; for(int i=0;i<n;i++){ count[nums[i]]++; } map<int,int>::iterator it; for(it=count.begin();it!=count.end();++it){ if(it->second>(n/2)) return it->first; } return 0; } };
相关文章推荐
- Windows Server 2012 如何实现多个用户远程桌面登陆?
- 数据库初识
- Git之VS2010实践
- 《利用python进行数据分析》读书笔记--第十章 时间序列(一)
- Caused by: java.lang.NoClassDefFoundError: org/springframework/ui/freemarker/FreeMarkerConfiguration
- http://a.codekk.com/detail/Android/grumoon/Volley%
- KETTLE 实现三表同步的问题
- Android Studio 好用的插件,这些基本是测试过好用的,或者我想用的~
- 丑数 UVA 136
- [Leetcode OJ] Merge Intervals
- oracle 11g-R2安装
- oracle 11g-R2安装
- 2662: [BeiJing wc2012]冻结
- 简单的签名 验签
- RxJava的map操作符
- 第三个Sprint ------第十一天
- -bash: pod: command not found
- tableView继续优化。
- 理解 Android Build 系统
- 多线程和多进程的区别(小结)