【LeetCode】169. Majority Element
2015-08-23 19:51
369 查看
题目:
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.
提示:
此题此题推荐三种比较好的方法:排序法(最简单):将数组排序,然后输出中位数;
随机方法:因为有大于50%的概率会一下子就随机抽中出现频率最大的数字,因此性能也算不错。具体方法就是在while循环中随机抽取一个数字,计算这个数字在数组中出现的次数,如果大于n/2次,那么就输出,不然的话就继续随机抽取下一个数字;
Moore Voting方法(最稳定,效率也很好):这个算法的时间复杂度是O(n),空间复杂度是O(1),我觉得是解决此题的最佳方法。
代码:
排序法:class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; } };
随机方法:
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); srand(unsigned(time(NULL))); while (true) { int idx = rand() % n; int candidate = nums[idx]; int counts = 0; for (int i = 0; i < n; i++) if (nums[i] == candidate) counts++; if (counts > n / 2) return candidate; } } };
Moore Voting方法:
class Solution { public: int majorityElement(vector<int>& nums) { int major, counts = 0, n = nums.size(); for (int i = 0; i < n; i++) { if (!counts) { major = nums[i]; counts = 1; } else counts += (nums[i] == major) ? 1 : -1; } return major; } };
相关文章推荐
- docker学习笔记2—创建一个nginx的镜像,并使用浏览器访问
- Mysql常用命令
- 苹果手表,只能留给孩子玩?
- 杭电(hdu)1106 排序
- java线 生产者和消费者
- 零基Github Page个人博客建立教程无限的自由流动
- 关于a different object with the same identifier value was already associated with the session错误的一种解决方法
- 用户管理命令
- C++多态
- 多线程操作同一个epoll fd同步
- 张国祥老师在宁波麒麟贸易集团公司北仑厂区讲授5S管理实战方法
- 总市值3862亿的创始人们在各阶段是怎么选女友的?
- 本地服务器网络连接配置
- UVA 10110
- annotation(注解) 解析与实例一
- org.hibernate.MappingException: Could not find a getter ...
- 【常用术语缩写】
- CAS票据验证失败一例
- 编写高质量代码改善C#程序的157个建议——建议138:事件和委托变量使用动词或形容词短语命名
- 简单卡尔曼滤波