Majority Element
来源:互联网 发布:2016网络诈骗事件 编辑:程序博客网 时间:2024/06/07 10:31
题目
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.
分析
这是在分治中的一个问题;无疑,所求的这个数出现的次数大于等于其他数出现的次数之和;所以可以用一个O(n)的方法来解决这个问题:
从头开始,记当前数字为cur;出现次数为1;然后开始遍历,若出现相同的数,计数加一,否则减一;如果记数减到小于0;则记cur为此时遍历到的数,最后剩下的cur必定是出现次数大于等于⌊ n/2 ⌋的那个数;
解答
class Solution {public: int majorityElement(vector<int>& nums) { int cur = nums[0]; int cnt = 1; for(int i = 1; i<nums.size(); i++) { if(nums[i]==cur)cnt++; else cnt--; if(cnt < 0) { cur = nums[i]; cnt = 1; } } return cur; }};
阅读全文
0 0
- majority element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- majority element
- Majority Element
- Majority Element
- DNN深度神经网络 的原理 以及 使用
- python中的函数
- tomcat
- J7613
- HBase的异常(二)
- Majority Element
- JSTL
- 复用的理解
- 发发发
- python3实现UDP协议的简单服务器和客户端
- 【面试题25】字符串的排列
- 我的网络编程学习之路——套接字地址结构
- ubuntu14.04配置caffe,cuda8.0+cudnn v6
- Git简介