boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - find Kth Largest Element 有没有更简化的解法
相关主题
问几个老算法题的最佳解法
lintcode 上的 Count of Smaller Number before itself
details 2nd smallest element in an array
请教一道题目
一FG家常见题
The time complexity on finding the kth largest element in a
请教一个老算法题, k-th largest sum
这题怎么做?
Leetcode Kth largest
一道热门的 Google 面试题
相关话题的讨论汇总
话题: 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版参与讨论
相关主题
一道热门的 Google 面试题
Find the K largest element in a sorted M*N array
请教个面试题
Kth Largest Element in an Array算法复杂度
Given an array of N integers from range [0, N] and one is missing. Find the missing number.
Find the Kth smallest element in 2 sorted
求解lintcode Majority Number III
largest bst 解法不理解的地方
关于质数(prime number)的算法题
问道算法题
相关话题的讨论汇总
话题: element话题: low话题: largest话题: int话题: kth