Question

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.

Solution 1 -- PriorityQueue

1. 将所有元素放入heap中

2. 依次用poll()取出heap中最大值

 public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || k > nums.length)
return 0;
int length = nums.length, index = length - k, result = 0;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(length,
new Comparator<Integer>(){
public int compare(Integer a, Integer b) {
return (a - b);
}
});
for (int i = 0; i < length; i++)
pq.add(nums[i]);
while (index >= 0) {
result = pq.poll();
index--;
}
return result;
}
}

Improvement

 public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || k > nums.length)
return 0;
int length = nums.length, index = k, result = 0;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(length, Collections.reverseOrder());
for (int i = 0; i < length; i++)
pq.add(nums[i]);
while (index > 0) {
result = pq.poll();
index--;
}
return result;
}
}

Solution 2 -- Quick Select

Quick Sort in Java

Average Time O(n)

 '''
a: [3, 2, 5, 1], 2
output: 2
''' def swap(a, index1, index2):
if index1 >= index2:
return
tmp = a[index1]
a[index1] = a[index2]
a[index2] = tmp def partition(a, start, end):
''' a[start:end]
pivot: a[end]
return: index of pivot
'''
pivot = a[end]
cur_big = start - 1
for i in range(start, end):
if a[i] >= pivot:
cur_big += 1
swap(a, cur_big, i)
cur_big += 1
swap(a, cur_big, end)
return cur_big def quick_select(a, k):
k -= 1
length = len(a)
start = 0
end = length - 1
while start < end:
index = partition(a, start, end)
if index == k:
return a[index]
if index > k:
# Note: end != index
end = index - 1
else:
# Note: start != index
start = index + 1
k = k - index
return -1 a = [3, 2, 5, 1]
k = 1
print(quick_select(a, k))

最新文章

  1. 牛逼的css3:动态过渡与图形变换
  2. PHP 正则表达式匹配中文字符
  3. Android 中沉浸式状态栏实现
  4. PHP程序设计经典300例
  5. Android表情功能
  6. 传智springMVC笔记
  7. 服务器进程为何通常fork()两次
  8. Codeforces Gym 100187D D. Holidays 排列组合
  9. 【转】Android平台下利用zxing实现二维码开发
  10. 使用java写一个小白计算器
  11. servlet第2讲(上集)----创建servlet实例(实现servlet接口)
  12. L1正则化及其推导
  13. python 序列
  14. jquery 动态获得主机地址
  15. OOAD与UML
  16. Centos7.3安装和配置Tomcat8
  17. Java中BufferedReader、InputStreamReader、Scanner和System.in区别
  18. C# System.Guid.NewGuid() 格式化
  19. c#接口与抽象类的区别(一)
  20. Gym - 100851F - Froggy Ford(dijkstra)

热门文章

  1. bzoj3393 [Usaco2009 Jan]Laserphones 激光通讯
  2. input里面check 状态检测
  3. wpf纯前台绑定
  4. Eclipse 里的 Classpath Variables M2_REPO 无法修改(maven)
  5. 盒子模型&amp;position定位
  6. Mysql日期函数,时间函数使用的总结
  7. XCode中在提示窗体中对已弃用的API接口画上红线
  8. 使用dojo的tree
  9. 【SVN Working copy is too old (format 10, created by Subversion 1.6)】解决方式
  10. [Immutable.js] Differences between the Immutable.js Map() and List()