leetcode229-Majority Element II(数组中出现最多的数II)
2016-04-02 20:07
531 查看
问题描述:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
给定一个数组,找到数组中所有出现次数多于n/3的数字。要求O(n)时间,O(1)空间。
问题求解:
1、超过n/3的元素个数最多2个
2、数组中连续3个数据为一组的话,一共n/3组,那么如果存在符合条件的元素,这个元素一定出现在某一个组内2次
O(n)时间,O(1)空间。
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
给定一个数组,找到数组中所有出现次数多于n/3的数字。要求O(n)时间,O(1)空间。
问题求解:
1、超过n/3的元素个数最多2个
2、数组中连续3个数据为一组的话,一共n/3组,那么如果存在符合条件的元素,这个元素一定出现在某一个组内2次
O(n)时间,O(1)空间。
class Solution { public: vector<int> majorityElement(vector<int>& nums) { int n=nums.size(); int cnt1=0, cnt2=0;//超过n/3的元素个数最多2个 //如果candidate1,2都置为0,若nums=[0,0,0]会重复计入!!! int candidate1=0, candidate2=1; for(int i=0;i<n;i++) {//(1)找出出现次数最多的2个元素 //每次存储2个元素,如果第3个元素与其中1个相同,则增加计数cnt1或cnt2, //否则,清除candidate1和candidate2,从下一个数据开始重新统计. if(candidate1 == nums[i]) { cnt1++; } else if(candidate2 == nums[i]) { cnt2++; } else if(cnt1 == 0) { candidate1=nums[i]; cnt1=1; } else if(cnt2 == 0) { candidate2=nums[i]; cnt2=1; } else { cnt1--; cnt2--; } } //(2)验证这2个元素是否满足条件,即出现的次数是否大于n/3; cnt1=0;cnt2=0; for(int i=0;i<n;i++) { if(nums[i] == candidate1) cnt1++; if(nums[i] == candidate2) cnt2++; } vector<int> res; if(cnt1 > n/3) res.push_back(candidate1); if(cnt2 > n/3) res.push_back(candidate2); return res; } };
相关文章推荐
- 设计模式(2)用例图之一
- 妙味课堂——HTML+CSS(第二课)
- 只为了你 幸福生活
- 如何使用ajax将json传入后台数据
- 寻找第n个数 与前n个数的几种方法
- instanceof运算符
- linux下支持伪静态和rewrite的实例
- This file is already open in an editor问题的解决方法
- 软考网络工程师
- leetcode---Remove Duplicates from Sorted Array
- Python简单的爬取网页信息并生成json文件与乱码解决小记
- android:interpolator
- Effective Java读书笔记(三):泛型、枚举、注解、异常
- Problem E: 建立链表(线性表)
- 总结
- struts、hibernate、spring这三个框架和J2EE是什么关系?
- spring事务隔离级别
- shell编程入门
- poj 1017 非常非常经典的贪心的算法
- L1-8. 求整数段和