169. Majority Element 破解思路
来源:互联网 发布:网络选修课刷课软件 编辑:程序博客网 时间:2024/06/06 07:36
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.
看到这个题目首先想到的是一种暴力破解法 利用 两个指针和sort函数进行解题 ,思路是 首先进行排序 接着统计每个数字出现的次数,二话不说上代码:
class Solution {public: int majorityElement(vector<int>& nums) { int n=nums.size(); sort(nums.begin(),nums.end()); vector<int>::iterator it; int count=1; for(it=nums.begin();it<=nums.end();it++) { if(*it==*(it+1)) { count++; } else { if(count>n/2) { return *it; } count=1; } } }初刷用了40ms,后来想到了c++ 特有的map<int,int> 容器,对每个数记录一个count ,代码如下
class Solution {public: int majorityElement(vector<int>& nums) { int n=nums.size(); vector<int>::iterator it; map<int,int> mapint; map<int,int>::iterator lt; for(it=nums.begin();it<nums.end();it++) { lt=mapint.find(*it); if(lt==mapint.end()) { // mapint.insert( pair <int, int> ( *it, 1 ) );两种方法都可以给mapint加入一个新的键值对 mapint[*it]=1; if(n==1) { return *it; } } else{ (*lt).second++; if( (*lt).second>n/2) { return *it; } } } }此刷是32ms,我顿觉可能我的能力就到这了,后来百度了一下该题目,真是有神解呀,moore voting algorithm,每次找出一对不相同的相邻数值,则都删掉,最后剩的那个就是要找的majority number,但是我们此时不用直接删除,只需要找出一个删到某一时间时,count最大的那个(好吧,我知道我表达不清楚)还是上代码吧
class Solution {public: int majorityElement(vector<int>& nums) { vector<int>::iterator it; int majority=0; int count=0; for(it=nums.begin();it<nums.end();it++) { if(count==0) { majority=*it; count++; } else{ if(majority!=*it) { count--; } else { count++; } } } return majority; } };此刷20ms
0 0
- 169. Majority Element 破解思路
- LeetCode- 169. Majority Element - 思路详解 -C++
- 第六周:[leetcode] 多思路解 169.Majority Element
- 169.Majority Element && 229. Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 169.Majority Element
- [leetcode] 169.Majority Element
- 169. Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- 169. Majority Element
- 169. Majority Element
- iOS工程自动打包并发布通过脚本实现
- AIR移动(Starling)开发笔记基础篇
- myeclipse个人注释模板
- excel文件导入
- HTML5和css3超实用的新属性集合
- 169. Majority Element 破解思路
- 关于native,transient,volatile,synchronized四个关键字的使用
- Hibernate之No row with the given identifier exists
- 关于UIScollView及其子类的在导航控制器
- 53.View the Exhibit and examine the data in the PROMOTIONS table.
- vsftp出现cannot change directory问题的解决方法
- 【杂谈】RBF径向基核函数&径向基网络
- 论copy_to_user返回值处理的重要性
- startActivityForResult和setResult详解