LeetCode-215.Kth Largest Element in an Array
2016-05-20 11:23
323 查看
https://leetcode.com/problems/kth-largest-element-in-an-array/
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
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
1
2
使用基于红黑树实现的multiset数据结构
3
快排
针对此题优化排序函数,
因为只要第k大,所以不用全排序
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.
1
public int FindKthLargest(int[] nums, int k) { Array.Sort(nums); return nums[nums.Length-k]; }
2
使用基于红黑树实现的multiset数据结构
int findKthLargest(vector<int>& nums, int k) { multiset<int> res; for (int num : nums) { if (res.size() < k) res.insert(num); else { if (num > *res.begin()) { res.erase(res.begin()); res.insert(num); } } } return *res.begin(); }
3
快排
public class Solution { public int FindKthLargest(int[] nums, int k) { Sort(nums, 0, nums.Length - 1); return nums[k-1]; } private void Sort(int[] nums, int l, int r) { if (l<r) { int i = l,j=r,x=nums[i]; while (i<j) { while (i < j && nums[j] <= x) j--; if (i < j) { nums[i] = nums[j]; i++; } while (i < j && nums[i] > x) i++; if (i < j) { nums[j] = nums[i]; j--; } } nums[i] = x; Sort(nums, l, i - 1); Sort(nums, i + 1, r); } } }
针对此题优化排序函数,
因为只要第k大,所以不用全排序
private void Sort(int[] nums, int l, int r,int k) { if (l<r) { int i = l,j=r,x=nums[i]; while (i<j) { while (i < j && nums[j] <= x) j--; if (i < j) { nums[i] = nums[j]; i++; } while (i < j && nums[i] > x) i++; if (i < j) { nums[j] = nums[i]; j--; } } nums[i] = x; if (i+1 == k) return; else if(i+1>k) Sort(nums, l, i - 1,k); else Sort(nums, i + 1, r,k); } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解