LeetCode OJ:Majority Element II(主元素II)
2015-10-30 11:56
162 查看
Given an integer array of size n, find all elements that appear more than
求主元素,这次的是大于sz/3就算是主元素,可以分为两轮查找,第一轮先查找元素数目较多的两个元素(可能不属于主元素),第二次再遍历来查找上面两个元素是否符合条件,代码如下:
⌊ n/3 ⌋times. The algorithm should run in linear time and in O(1) space.
求主元素,这次的是大于sz/3就算是主元素,可以分为两轮查找,第一轮先查找元素数目较多的两个元素(可能不属于主元素),第二次再遍历来查找上面两个元素是否符合条件,代码如下:
class Solution { public: vector<int> majorityElement(vector<int>& nums) { int m1, m2; int count1, count2; vector<int> ret; int sz = nums.size(); if(!sz) return ret; m1 = nums[0]; m2 = 0; count1 = 1; count2 = 0; for(int i = 1; i < sz; ++i){ if(m1 == nums[i]) count1++; else if(m2 == nums[i]) count2++; else if(count1 == 0){ count1++; m1 = nums[i]; }else if(count2 == 0){ count2++; m2 = nums[i]; }else{ count1--; count2--; } } count1 = count2 = 0; for(int i = 0; i < sz; ++i){ if(nums[i] == m1) ++count1; if(nums[i] == m2) ++count2; } if(count1 > sz/3) ret.push_back(m1); if(m1 != m2) if(count2 > sz/3) ret.push_back(m2); return ret; } };
相关文章推荐
- Servlet 实例hello world
- 一个登录的功能
- SurfaceView绘制音乐柱形图
- WCF 学习
- Andorid读写全局配置文件的方法
- 避免Cisco设备被暴力破解登陆TELNET/SSH...
- 随机数组
- ASP.NET MVC实现网站验证码功能
- 获取指定目录下的所有文件名
- 优雅sql脚本
- CoreData
- jQuery-easyUI的使用:combobox实现联动选择及自动搜索
- JSP页面数据展示:分组数据展示
- android怎么实现自动接听
- Swift完整教程系列
- android GridLayout 设置item间距方式
- AVILib Android AVI录像文件封装
- POJ1469 COURSES
- 深入研究java.lang.Runtime类
- bones脚本篇 - 实现一个简单的列表