LeetCode-215. Kth Largest Element in an Array
2017-09-25 14:21
453 查看
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.
查找一个序列中第K大的数字。
可以使用快速选择算法
http://blog.csdn.net/x_iya/article/details/78077933
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.
查找一个序列中第K大的数字。
可以使用快速选择算法
http://blog.csdn.net/x_iya/article/details/78077933
package solutions._215; /** * 215. Kth Largest Element in an Array */ class Solution { private int partition(int[] arr, int left, int right) { int pivot = arr[left]; while (left < right) { while (left < right && arr[right] >= pivot) { right--; } arr[left] = arr[right]; while (left < right && arr[left] <= pivot) { left++; } arr[right] = arr[left]; } arr[left] = pivot; return left; } private int QuickSelect(int[] arr, int left, int right, int k) { if (left < right) { int pivot = partition(arr, left, right); System.out.println("pivot = " + pivot); if (pivot == k - 1) { return arr[pivot]; } else if (pivot > k - 1) { return QuickSelect(arr, left, pivot - 1, k); } else { return QuickSelect(arr, pivot + 1, right, k); } } return arr[left]; } public int findKthLargest(int[] nums, int k) { return QuickSelect(nums, 0, nums.length - 1, nums.length - k + 1); } public static void main(String[] args) { Solution solution = new Solution(); int[] arr = {1}; System.out.println(solution.findKthLargest(arr, 1)); } }
相关文章推荐
- leetcode 215. Kth Largest Element in an Array
- leetCode:215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- [leetcode] 215. Kth Largest Element in an Array
- 【LeetCode】215. Kth Largest Element in an Array (2 solutions)
- LeetCode 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- 【LeetCode】 215. Kth Largest Element in an Array
- [leetcode]215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array 堆排序的简单应用 + 快速排序
- Leetcode 215. Kth Largest Element in an Array
- Leetcode:215. Kth Largest Element in an Array
- LeetCode 215. Kth Largest Element in an Array
- 【LeetCode】215. Kth Largest Element in an Array (Medium)
- LeetCode题解系列--215. Kth Largest Element in an Array
- [LeetCode] 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- <LeetCode OJ> 215. Kth Largest Element in an Array
- Leetcode 215. Kth Largest Element in an Array