LeetCode-215.Kth Largest Element in an Array
来源:互联网 发布:java入门教程视频 编辑:程序博客网 时间:2024/06/05 18:49
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 [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
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); } }
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
- Android 6.0 运行时权限处理
- xcode每次修改都需要clean后才能生效
- android studio部署手机导致unable to detect adb version的处理
- 在java求学java学习,java教程之路上四个禁忌,你知道吗?
- 代码加约束VFL语法的详细使用介绍(代替Autolayout进行布局,比Autolayout更简单明了,生动直观)
- LeetCode-215.Kth Largest Element in an Array
- iOS 左右两列按钮之间进行连线
- IOS9需要升级提升的点
- JSON的输出方式
- 电子商务网站商品推荐案例分析
- C++第六次实验—循环(实验)
- /dev/shm应该设置多大Oracle 实例启动时才能不报ORA-00845
- CodeForces 509B Painting Pebbles
- 0.1 Spark Streaming 实现思路与模块概述