Majority Element
来源:互联网 发布:网络水晶头怎么接 编辑:程序博客网 时间:2024/04/24 21:41
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.
思路:如果不相同就成对删除,剩下的就是the majority element。 如何成对删除,可以用一个计数器,相同就+,不同就-,为0的时候更新candidate。
Ref:http://www.cnblogs.com/ganganloveu/p/4177690.html
class Solution {public: int majorityElement(vector<int> &num) { int candidate = 0; int count = 0; for (int i = 0; i < num.size(); i++) { if (count == 0) { candidate = num[i]; count = 1; } else { if (candidate == num[i]) { count++; } else { count--; } } } return candidate; }};
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
- spring注解入门
- 编写高质量的Makefile
- js对象和jQuery对象转换
- vector::erase():容器删除
- 百度,淘宝,腾讯三大巨头HTML页面规范分解
- Majority Element
- c-3 预处理指令 宏 条件编译 文件包含
- 让人死去活来的cocos2d-x安卓开发环境搭建(windows+eclipse+ndk)
- -L、-rpath和-rpath-link的区别
- Javascript escape 解决 Jquery Ajax 异步请求 URL中文传参乱码问题 一般处理程序Handler获取参数
- Android调用支付宝快捷支付时提示"系统繁忙,请稍后再试(ALI64)"错误
- ASP.NET MVC 4 插件化架构简单实现-思路篇
- 读取一个文件每行中的各列数据
- 急求解答!!!!!!!!!!!!!!