Redian新闻
>
find Kth Largest Element 有没有更简化的解法
avatar
find Kth Largest Element 有没有更简化的解法# JobHunting - 待字闺中
S*C
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/
avatar
y*9
2
我能想到的2nd largest 是 n + logn - 2 次对比。
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。