169. Majority Element
来源:互联网 发布:编程cim是做什么的 编辑:程序博客网 时间:2024/06/07 05:56
/*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.1.排序 查找2.hash表计数 遍历3.由于一定存在主要的元素且数量大于n/2,所有可以使用计数抵消的方法,选第一个元素为主要元素,如果下一个元素与之相同则计数加一,否则计数减一;当计数值为0时,在选择下一个元素为主要元素,重复上述过程,最后主要元素的值即使所求。*/#include <iostream>#include <vector>using namespace std;class Solution {public: int majorityElement(vector<int>& nums) { int major=nums[0],cnt=1; for(int i=1;i<nums.size();i++) { if(cnt==0) { major=nums[i]; cnt++; } else if(major==nums[i]) cnt++; else cnt--; } return major; }};int main(){ Solution mys; vector<int> nums={6,5,5}; cout<<mys.majorityElement(nums)<<endl; return 0;}
阅读全文
0 0
- 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
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- 经验模态分解
- Python学习第一课
- nodejs爬虫参考
- python maximum recursion depth exceeded解决方式
- 倒水(rms2017模拟2-1)* 【推理】
- 169. Majority Element
- 执行HBase建表操作,每次创建表HRegionServer都会挂掉,而 HMaster还在!RetriesExhaustedException: Can't get the locations
- POJ2699 The Maximum Number of Strong Kings (maxflow)
- 由四个点求两条线段交点代码实现
- CentOS 7 下安装Chrome浏览器
- 二叉树遍历(已知先序、中序求后序)
- 深入学习APC
- dom解析
- java中的接口和抽象类的区别