多数投票算法
2015-10-15 22:20
399 查看
今天在leetcode看到一个题目: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.
主要简单的想法是将数组排序,因为多数的元素超过一半,因此排序后中间的元素必定是要求的多数元素。代码如下:
时间复杂度为O(nlogn)。那能否只需O(n)时间复杂度内完成任务呢?答案是可以的,一种思路是利用hashmap。另一种是就是 Boyer–Moore majority vote algorithm 。算法思路是:
每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。
相应的Majority Element 的 Solution 为:
我的Github: leetcode解答https://github.com/wanggang3333
leetcode-majorityelement :majorityelement
参考:
1.【leetcode 哈希表】Majority Element ——csdn
2.Moore's voting algorithm——csdn
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
主要简单的想法是将数组排序,因为多数的元素超过一半,因此排序后中间的元素必定是要求的多数元素。代码如下:
public class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; } }
时间复杂度为O(nlogn)。那能否只需O(n)时间复杂度内完成任务呢?答案是可以的,一种思路是利用hashmap。另一种是就是 Boyer–Moore majority vote algorithm 。算法思路是:
每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。
相应的Majority Element 的 Solution 为:
//Boyer–Moore majority vote algorithm public class Solution { public int majorityElement(int[] nums) { int result = 0; int count = 0; for(int i = 0; i < nums.length; ++i) { if(count == 0) { result = nums[i]; count++; } else if(result == nums[i]) { count++; } else { count--; } } return result; } }
我的Github: leetcode解答https://github.com/wanggang3333
leetcode-majorityelement :majorityelement
参考:
1.【leetcode 哈希表】Majority Element ——csdn
2.Moore's voting algorithm——csdn
相关文章推荐
- 【cl】java变量
- LeetCode 2:Add Two Numbers
- 堆和栈的区别(个人感觉挺不错的)
- 杂想
- Swift利用inout交换两个数的位置
- Oracle归档目录 和 DB_RECOVERY_FILE_DEST
- {Effective Java} Chap 10 Concurrency
- VBscript常用函数
- puppet file资源详解
- puppet package资源详解
- IE低版本(6-9)CSS hack
- CSS3属性之一:border-radius
- swift 2.0 分支语句 if...else & switch
- C++实现RTMP协议发送H.264编码及AAC编码的音视频,摄像头直播
- 0day-shellcode简单伪装分析NO.2
- libevent
- BookStrap中关于button和图片的注意点
- web前端学习笔记03
- hdoj 2296 Ring 【AC自动机 + dp】
- 关于键盘弹出挡住输入框的问题