(Leetcode)215.Kth Largest Element in an Array(medium)
来源:互联网 发布:app数据查询 编辑:程序博客网 时间:2024/06/06 20:54
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大的数,采用分治的方法,先任取一个数作为标准(我取得是第一个数),遍历数组,将比标准大的放左边,比标准小的放右边,得到标准数在数组中的排位x,若x即为k,则返回标准数,若k比x小或大,则在相应区域重复上面步骤,直到x与k相同。
我的代码:
class Solution {public: int findKthLargest(vector<int>& nums, int k) { int i = 0; while (i<nums.size()) { if (nums.size() == 1) return nums[0]; int pivot = nums[i]; int x = i + 1; int y = i + 1; //用于确立pivot的位置 while (y < nums.size()) { if (nums[y] > pivot) { swap(nums[x], nums[y]); x++; } y++; } swap(nums[i], nums[x-1]); //x-1即为pivot所在的位置 if (x-1 == (k-1)) { return nums[x-1]; } else if ((k-1) < x-1) { continue; } else { i = x; continue; } } return 0; }};
0 0
- Leetcode 215. Kth Largest Element in an Array (Medium) (cpp)
- (Leetcode)215.Kth Largest Element in an Array(medium)
- 【LeetCode】215. Kth Largest Element in an Array (Medium)
- Leetcode 215. Kth Largest Element in an Array[medium]
- LeetCode 215. Kth Largest Element in an Array(Medium)
- LeetCode 215. Kth Largest Element in an Array (Medium)
- [Leetcode 215, Medium] Kth Largest Element in an Array
- 215. Kth Largest Element in an Array (Medium)
- 第二周 leetcode 215. Kth Largest Element in an Array(Medium)
- 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
- Struts2.0学习---第一个程序
- android开发实用工具
- LightOJ1285->极角排序
- 洛谷 P1024 [NOIP2001 T1] 一元三次方程求解
- 3.4 HotSpot算法实现
- (Leetcode)215.Kth Largest Element in an Array(medium)
- IntelliJ IDEA 使用教程
- POJ 3667
- Android中的Adapter 详解(三)
- 二维数组中的查找
- ADF(js)--如何控制按钮类组件不往后台发送请求
- oracle表相关知识
- 两个链表的第一个公共结点
- 41. First Missing Positive[hard]