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 ...
随机推荐
- Android去除系统自带动画的两种方法
方法一: 在startActivity()或者finish()后紧跟调用: ((Activity) mContext).overridePendingTransition(0, 0); 方法二: 在一 ...
- <php>过时方法连接数据库代码
<?php //1.生成链接 $db_connect = mysql_connect("localhost","root","20982239& ...
- ipython with ubuntu
在Linux环境下,其实IDE环境配置比较容易配.所以建议用linux做开发. 首选启动终端:Ctrl+Alt+T sudo apt-get update sudo apt-get install p ...
- log4net使用具体解释
说明:本程序演示怎样利用log4net记录程序日志信息.log4net是一个功能著名的开源日志记录组件.利用log4net能够方便地将日志信息记录到文件.控制台.Windows事件日志和数据库(包含M ...
- [置顶] ./build_native 时出现please define NDK_ROOT
在一次帮朋友弄cygwin交叉编译时出现了这个问题 cygwin是按照成功了,make-v,以及gcc-v都没出现问题,就是在./build_native 时出现please define NDK_R ...
- 分页搜索查询sql
select * from (select t.*,rownum no from " + table + " t where scbj=0)where (no>(" ...
- .net 调用Oracle.Data.Access 组件提供的用于批量操作的方法—获取数据库表结构方法和跟参数赋值方法
1./// <summary> /// 获取当前目标表结构 /// </summary> /// <param name="tableName"> ...
- 1、solr 查询
solr查询参数: q 查询的关键字,此参数最为重要,例如,q=id:1,默认为q=*:*, fl 指定返回哪些字段,用逗号或空格分隔,注意:字段区分大小写,例如,fl= id,title,sor ...
- poj1562 DFS入门
K - 搜索 Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:10000KB 64bit I ...
- (转) Python in NetBeans IDE 8.0
原地址: https://blogs.oracle.com/geertjan/entry/python_in_netbeans_ide_8 Copy this to the clipboard: ht ...