由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - find Kth Largest Element 有没有更简化的解法
相关主题
问几个老算法题的最佳解法Leetcode Kth largest
lintcode 上的 Count of Smaller Number before itself一道热门的 Google 面试题
details 2nd smallest element in an arrayFind the K largest element in a sorted M*N array
请教一道题目请教个面试题
一FG家常见题Kth Largest Element in an Array算法复杂度
The time complexity on finding the kth largest element in aGiven an array of N integers from range [0, N] and one is missing. Find the missing number.
请教一个老算法题, k-th largest sumFind the Kth smallest element in 2 sorted
这题怎么做?求解lintcode Majority Number III
相关话题的讨论汇总
话题: element话题: low话题: largest话题: int话题: kth
进入JobHunting版参与讨论
1 (共1页)
S*******C
发帖数: 822
1
以下的O(n) time, O(1) space解法还能再简化吗?
Kth Largest Element
18%
Accepted
Find K-th largest element in an array.
Note
You can swap elements in the array
Example
In array [9,3,2,4,8], the 3rd largest element is 4
In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4
, 3rd largest element is 3 and etc.
Challenge
O(n) time, O(1) space
class Solution {
public static void main(String args[]) {
Solution test = new Solution();
int[] a = { 5, 4, 1, 3, 2};
ArrayList list = new ArrayList();
for (int i : a)
list.add(i);
for (int i = 1; i <= a.length; i++)
System.out.println(test.kthLargestElement(i, list));
}
//param k : description of k
//param numbers : array of numbers
//return: description of return
public int kthLargestElement(int k, ArrayList list) {
if (list == null || list.size() < k)
throw new Error("The kth largest element does not exist in given
list");
int start = 0, end = list.size() - 1;
k = list.size() - k;//comment this statement to find kth smallest
element
// if start == end we reached the kth element
while (start < end) {
int low = start, high = end, mid = (low + high) / 2;
int pivot = list.get(mid);
while (low < high) {
if (list.get(low) >= pivot) { // put large values at the end
int temp = list.get(high);
list.set(high, list.get(low));
list.set(low, temp);
high--;
} else{ // the value is smaller than the pivot, skip
low++;
}
}
if (list.get(low) > pivot)
low--;
// the low pointer is on the end of the first k elements
if (k <= low)
end = low;
else
start = low + 1;
}
return list.get(k);
}
};
http://lintcode.com/en/problem/kth-largest-element/
y****9
发帖数: 252
2
我能想到的2nd largest 是 n + logn - 2 次对比。
1 (共1页)
进入JobHunting版参与讨论
相关主题
求解lintcode Majority Number III一FG家常见题
largest bst 解法不理解的地方The time complexity on finding the kth largest element in a
关于质数(prime number)的算法题请教一个老算法题, k-th largest sum
问道算法题这题怎么做?
问几个老算法题的最佳解法Leetcode Kth largest
lintcode 上的 Count of Smaller Number before itself一道热门的 Google 面试题
details 2nd smallest element in an arrayFind the K largest element in a sorted M*N array
请教一道题目请教个面试题
相关话题的讨论汇总
话题: element话题: low话题: largest话题: int话题: kth