Kth Largest Element in an Array LeetCode Java
来源:互联网 发布:vb中跳出for循环 编辑:程序博客网 时间:2024/05/16 08:16
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.
刚看这道题目的时候, 首先想法是使用构造大根堆的方式实现。本来想在讨论区参考一下具体做法,但是看了一下讨论区的内容,才恍然大悟,java的priorityQueue不就是通过堆来实现的吗?直接用就好了。。。。
同时,在讨论区看到了一个多个解法的帖子,感觉写的挺不错的,就转过来了(原地址:https://leetcode.com/discuss/36966/solution-explained):
方法一
排序法
public int findKthLargest(int[] nums, int k) { final int N = nums.length; Arrays.sort(nums); return nums[N - k];}
方法二
priorityQueue
public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> priorityQueue=new PriorityQueue<Integer>(); for(int i:nums){ priorityQueue.add(i); if(priorityQueue.size()>k){ priorityQueue.poll(); } } return priorityQueue.poll(); }
方法三
使用选择算法,其实就是快排用到的思路
public int findKthLargest2(int[] nums,int k){ k=nums.length-k; int lo=0; int hi=nums.length-1; while(lo<hi){ final int j=partition(nums, lo, hi); if(j<k){ lo=j+1; }else if(j>k){ hi=j-1; }else { break; } } return nums[k]; } private int partition(int[] a,int lo,int hi){ int i=lo; int j=hi+1; while(true){ while(i<hi && less(a[++i], a[lo])); while(j>lo && less(a[lo], a[--j])); if(i>=j) break; exch(a, i, j); } exch(a, lo, j); return j; } private void exch(int[] a,int i,int j){ final int tmp=a[i]; a[i]=a[j]; a[j]=a[i]; } private boolean less(int v,int w){ return v<w; }
0 0
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- LeetCode -- Kth Largest Element in an Array
- MySQL导入sql脚本错误:2006 - MySQL server has gone away
- myeclipse2013/2015更新ADT-please update ADT to the latest version
- docker使用总结
- 二叉树的三种遍历方法
- Unity3D手游-横版ACT游戏完整源码下载
- Kth Largest Element in an Array LeetCode Java
- sublime text 3支持中文输入法
- Android中的android:layout_width和android:width区别
- Understanding ASP.NET View State
- mysql:Variable 'character_set_client' can't be set to the value of 'NULL'解决
- C#中通过COM读写Excel
- css 完全居中 方便查阅
- MFC控件的使用
- 开发常用网站论坛整理http://www.apkbus.com/android-182423-1-1.html