Leetcode Kth Largetst element
2015-06-02 10:55
337 查看
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.
[code]public class Solution { public int findKthLargest(int[] nums, int k) { return kth(nums,0, nums.length-1, k); } int kth(int[]nums, int start, int end, int k) { int r=nums[end]; int i=start-1, j=start; while(j<end) { if(nums[j]<=r) { swap(nums,++i,j++); } else j++; } swap(nums,++i,end); if(end-i+1==k)return r; else if(end-i+1<k)return kth(nums, start, i-1, k-end+i-1); else return kth(nums, i+1, end, k); } void swap(int[] nums, int i ,int j) { int t=nums[i]; nums[i]=nums[j]; nums[j]=t; } }
相关文章推荐
- [leetcode 230]Kth Smallest Element in a BST----求二叉搜索树的第K小值
- leetcode---Kth Smallest Element in a Sorted Matrix
- [leetcode-215]Kth Largest Element in an Array(java)
- [Leetcode] #230 Kth Smallest Element in a BST
- [Leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告
- Leetcode[215]-Kth Largest Element in an Array
- Leetcode230 Kth Smallest Element in a BST
- [LeetCode] Kth Largest Element in an Array
- leetcode(378):Kth Smallest Element in a Sorted Matrix
- 【LeetCode】 378. Kth Smallest Element in a Sorted Matrix
- Leetcode 215 Kth Largest Element in an Array(快速选择)
- 【LeetCode-215】Kth Largest Element in an Array
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- leetcode-Kth Largest Element in an Array
- LeetCode|Kth Largest Element in an Array
- [LeetCode 230] Kth Smallest Element in a BST
- LeetCode-Kth Smallest Element in a BST-解题报告
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode-230]Kth Smallest Element in a BST
- *LeetCode-Kth Largest Element in an Array