【leetcode】Majority Element II,Majority element algorithm
2015-09-08 17:04
465 查看
My idea comes from Majority Vote algroithm(http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html) .Now we vote two numbers simultaneously. if the next number is differents from them both.then the two numbers’ votes minus one. If some number’s vote comes zero,then vote the next number.Every time vote minus,it is the same that we remove the three numbers from the array.And the majority elemnts of original still are the majority elements in the end. So check t1 and t2 are the majority elements of original array at last.
vector<int> majorityElement(vector<int>& nums) { int t1,t2,n1=0,n2=0; //numbers t1 and t2,votes' numbers n1,and n2. for(int i=0;i<nums.size();++i) { if(n1!=0&&t1==nums[i]){++n1;continue;} if(n2!=0&&t2==nums[i]){++n2;continue;} if(n1==0){ t1=nums[i];++n1;continue;} if(n2==0){ t2=nums[i];++n2;continue;} --n1;--n2; } int z1=0,z2=0; for(int i=0;i<nums.size();++i) { if(n1>0){ if(nums[i]==t1) ++z1;} if(n2>0) {if(nums[i]==t2) ++z2;} } vector<int> ret; //check t1 and t2. if(z1>nums.size()/3) ret.push_back(t1); if(z2>nums.size()/3) ret.push_back(t2); return ret; }
相关文章推荐
- google mock分享
- 1062 - Duplicate entry '20150820048' for key 'goods_serial'
- Algorithms—110.Balanced Binary Tree
- Django架设blog步骤
- Goods:我的订单查询分页
- Golang在京东列表页实践总结
- 11292 - Dragon of Loowater(贪心)
- Google Analytics自定义广告系列
- Beego环境搭建和bee工具安装使
- 算法系列(一) Google方程式
- 移除百度地图LOGO和版权信息
- Category添加属性
- Leetcode Algorithm No.242 Valid Anagram
- 【Django】template中实现加减乘除数学运算[加法 减法 乘法 除法]
- oc中protocol、category和继承的区别
- oc中protocol、category和继承的区别
- 【Django】 终端打印出错信息
- 【Django】 密码加密
- 【Django】 国际化
- [译]Google新logo是如何缩减13000字节的