Majority Element
来源:互联网 发布:原创文章是什么算法 编辑:程序博客网 时间:2024/04/26 15:52
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.
题意:找数组里数目超过一半的那个元素。
思路:排序,然后中间那个元素
public int majorityElement(int[] num) { Arrays.sort(num); return num[num.length/2];}
看了solution,好多种方法 = =
又做了里面那种叫做Moore voting algorithm的,可以达到O(n)
We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
- If the counter is 0, we set the current candidate to x and the counter to 1.
- If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
public int majorityElement(int[] num) { int candidate = num[0]; int counter = 1; for (int i=1; i<num.length; i++) { if (counter == 0) { candidate = num[i]; counter++; } else { if (num[i] == candidate) { counter++; } else { counter--; } } } return candidate;}
网上搜了一下,有大神说 “每找出两个不同的element,则成对删除。最终剩下的一定就是所求的。”
这么一说马上豁然开朗。
solution还介绍了个分治方式的,谷歌搜了下,看到一份解题报告,只有伪码,感觉伪码好像是不对的,还是跟着实现,果然没过 = =
坐等大神代码
procedure GetMajorityElement(a[1...n])Input: Array a of objectsOutput: Majority element of aif n = 1: return a[1]k = n/2elemlsub = GetMajorityElement(a[1...k])elemrsub = GetMajorityElement(a[k+1...n]if elemlsub = elemrsub:return elemlsublcount = GetFrequency(a[1...n],elemlsub)rcount = GetFrequency(a[1...n],elemrsub)if lcount > k+1:return elemlsubelse if rcount > k+1:return elemrsubelse return NO-MAJORITY-ELEMENT
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
- [OpenGL ES 03]3D变换:模型,视图,投影与Viewport
- 第十七周项目四日期结构体
- 九度OJ 1041 Simple Sorting (排序,STL)
- ListView动态修改列宽
- VS2010编译遇到的问题
- Majority Element
- 【纯代码】TableView简单配置
- 关于我的开源项目RedisFile讲解 一
- 打开别人的android时报错缺少android环境的解决办法
- iOS AES 与SHA256加密字符串
- Solr的一些查询参数
- 总结:自动生成网页截图(Screenshot)方法
- iOS中多线程编程
- [C++]LeetCode: 53 Unique Binary Search Trees