169. Majority Element
来源:互联网 发布:fitbit手环哪款好 知乎 编辑:程序博客网 时间:2024/06/16 04:56
169. Majority Element
题目
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.
翻译
给定大小为n的数组,找到多数元素。多数元素是出现次数 ⌊n/2⌋ 以上的元素。
您可以假定该数组不为空,并且多数元素始终存在于数组中。
解题思路
如果正常使用排序算法的话然后进行遍历的话时间复杂度达到了O(nlogn),这不是一个好的方式。
一共有两个思路都能达到O(n),第一个是用计数器,过半数的元素计数器最终一定会计数到它,代码如下
public class Solution { public int majorityElement(int[] nums) { int count=0; int element=0; for(int i=0;i<nums.length;i++){ if(count==0){ element=nums[i]; count=1; }else{ if(element==nums[i]){ count++; }else{ count--; } } } return element; }}
另一个很神奇的思路是使用随机数,数学期望是2*O(n),也就是O(n),因为元素过半,所以每次随机数有50%的几率会选中该元素,所以时间复杂度也比较低,代码如下
class Solution {public: int majorityElement(vector<int> &num) { int count = 0; for(;;) { if(num.size() == 1) return num[0]; else { int i = rand() % (num.size() - 1); for(int j = 0; j < num.size(); j++) { if(num[j] == num[i]) count++; } if(count > (num.size() / 2)) return num[i]; else { count = 0; continue; } } } } };
欢迎加入中科院开源软件自习室:631696396
阅读全文
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
- Lintcode——排序专题总结
- code::block中常用的快捷键
- Java线程面试题Top50
- 时间同步,ntpd、ntpdate
- 弹窗动画
- 169. Majority Element
- Win7系统打开网页提示应用程序已被JAVA安全阻止的解决方法
- Android---------ViewPager+Fragment实现界面的转换(颜色变化)
- CentOS6.8 yum 安装 mysql步骤
- 有监督回归:稀疏学习
- 斐波那契数
- 操作系统复习-2.3 进程同步
- 百度员工离职忠告:你我都是平庸人,要学会适应规则
- Python中列表、元组、元组的列表和NumPy中数组、数组的列表的比较