Majority Element II 解答
Question
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
A Linear Time Voting Algorithm
Solution 1 -- Binary Search
我们发现一个规律。如果是大于 1/k 的majority,排好序的数组中,它们可能出现的位置是
len / k, len * 2/ k, len * 3 / k, ...
所以我们可以依次用二分查找法查找在 len * i / k 的各个点的start和end position,然后算长度,判断是否满足条件。
动态一些的方法是下一个待判断点的坐标为 prevEnd + len / k + 1

如图,绿线为start point 红线为end point
Time complexity O(n log n), space O(1)
public class Solution {
public List<Integer> majorityElement(int[] nums) {
Arrays.sort(nums);
List<Integer> result = new ArrayList<Integer>();
int len = nums.length;
if (len < 1)
return result;
int candidate1 = nums[len / 3];
// Find start and end of candidate1
int[] range1 = searchRange(nums, candidate1);
int num1 = range1[1] - range1[0] + 1;
if (num1 > len / 3)
result.add(candidate1);
// Find start and end of candidate2
int index = len / 3 + range1[1] + 1;
if (index >= len)
return result;
int candidate2 = nums[index];
int[] range2 = searchRange(nums, candidate2);
int num2 = range2[1] - range2[0] + 1;
if (num2 > len / 3 && candidate2 != candidate1)
result.add(candidate2);
return result;
}
private int[] searchRange(int[] nums, int target) {
int start = 0, end = nums.length - 1, mid;
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
if (nums[mid] >= target)
end = mid;
else
start = mid;
}
if (nums[start] == target)
result[0] = start;
else if (nums[end] == target)
result[0] = end;
start = 0;
end = nums.length - 1;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
if (nums[mid] > target)
end = mid;
else
start = mid;
}
if (nums[end] == target)
result[1] = end;
else if (nums[start] == target)
result[1] = start;
return result;
}
}
Solution 2 -- Moore Voting Algorithm
Time complexity O(n), space cost O(1)
public class Solution {
public List<Integer> majorityElement(int[] nums) {
int count1 = 0, count2 = 0;
Integer num1 = null, num2 = null;
int len = nums.length;
for (int current : nums) {
if (num1 != null && current == num1.intValue()) {
count1++;
} else if (num2 != null && current == num2.intValue()) {
count2++;
} else if (num1 == null || count1 == 0) {
num1 = current;
count1 = 1;
} else if (num2 == null || count2 == 0) {
num2 = current;
count2 = 1;
} else {
count1--;
count2--;
}
}
// Check whether num1, num2, num3 are valid
count1 = 0;
count2 = 0;
for (int current : nums) {
if (current == num1.intValue()) {
count1++;
} else if (current == num2.intValue()) {
count2++;
}
}
List<Integer> result = new ArrayList<Integer>();
if (count1 > len / 3) {
result.add(num1);
}
if (count2 > len / 3) {
result.add(num2);
}
return result;
}
}
Majority Element II 解答的更多相关文章
- LeetCode(169)Majority Element and Majority Element II
一个数组里有一个数重复了n/2多次,找到 思路:既然这个数重复了一半以上的长度,那么排序后,必然占据了 a[n/2]这个位置. class Solution { public: int majorit ...
- Majority Element,Majority Element II
一:Majority Element Given an array of size n, find the majority element. The majority element is the ...
- leetcode 169. Majority Element 、229. Majority Element II
169. Majority Element 求超过数组个数一半的数 可以使用hash解决,时间复杂度为O(n),但空间复杂度也为O(n) class Solution { public: int ma ...
- Majority Element(169) && Majority Element II(229)
寻找多数元素这一问题主要运用了:Majority Vote Alogrithm(最大投票算法)1.Majority Element 1)description Given an array of si ...
- 【LeetCode】229. Majority Element II
Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...
- LeetCode169 Majority Element, LintCode47 Majority Number II, LeetCode229 Majority Element II, LintCode48 Majority Number III
LeetCode169. Majority Element Given an array of size n, find the majority element. The majority elem ...
- 【刷题-LeetCode】229. Majority Element II
Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...
- [LeetCode] Majority Element II 求众数之二
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...
- Leetcode: Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...
随机推荐
- SOA 新业务语言 新系统架构——什么是SOA
原文地址:http://blog.csdn.net/ichaos/archive/2008/01/20/2054377.aspx SOA的概念是Gartner在1996年提出来的,并于2002年12月 ...
- hdu 5167 Fibonacci(预处理)
Problem Description Following is the recursive definition of Fibonacci sequence: Fi=⎧⎩⎨01Fi−1+Fi−2i ...
- pyqt搜索指定信息 github处找到,谢谢这位朋友的帮助了
def tabunqi(self,text): #第一遍添加之后,不提示,当第二次添加相同的数据时,就提示下 text1=str(text) items = self.downwid ...
- AngularJs学习笔记4——四大特性之双向数据绑定
双向数据绑定 方向1:模型数据(model)绑定到视图(view) 实现方法:①.{{model变量名}} ②.常用指令(ng-repeat) 方向2:将视图(view)中用户输入的数据绑定到模型数 ...
- JavaScript 精髓整理篇之一(对象篇)postby:http://zhutty.cnblogs.com
废话篇头: 由于工作关系,所以写博文的时间有那么点~~,其实是输入法太懒了,都是输入法的错~~ 这一系列的博客将总结所有关于JavaScript语言的精髓,适合0基础到大师级别人物阅读. <Ja ...
- SQL函数简述
数字函数ABS 取绝对值 POWER 乘方 LN 10为底数取幂SQRT 平方根 EXP e的n次乘方 LOG(m,n) m为底数n取幂数学运算函数:ACOS ATAN ATAN2 COS COSH ...
- DEV SIT UAT
DEV环境:DEV顾名思义就是develop,即代码开发的环境.SIT环境:System Integration Test系统集成测试,开发人员自己测试流程是否走通.UAT环境:User Accept ...
- 关于java中根据身份证求生日和年龄的问题
/*这个也没什么大的功能,也没什么安全验证,只是对输入的身份证号码的长度进行了验证.其他的功能可以自己添加.*/import java.util.*; import java.util.Scanner ...
- [MVC4-基礎] 連動DropDownList - 使用jQuery、JSON
剛開始學MVC4,以下是一些基礎的學習筆記! 先展示一下結果: 1.選擇申請部門 2.選好後申請部門鎖住防止USER修改並載入該部門所擁有的設備類型 一.資料庫 dept mf_fx 二.View ( ...
- 重写OnPaint事件对窗体重绘(显示gif动画) 实例2
/// <summary> /// 可显示Gif 的窗体 /// </summary> public class WinGif : Form { private Image _ ...