2017-09-12 LeetCode_215 Kth Largest Element in an Array

来源:互联网 发布:电脑隐藏软件 编辑:程序博客网 时间:2024/06/07 19:38

215. 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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

solution:

class Solution {
2
public:
3
    int findKthLargest(vector<int>& nums, int k) {
4
        int d, s = 0, e = nums.size()-1;
5
        do {
6
            int m = nums[s];
7
            int i = s, j = e;
8
            while (i < j) {
9
                while (nums[j] <= m && i < j) j--;
10
                nums[i] = nums[j];
11
                while (nums[i] >= m && i < j) i++;
12
                nums[j] = nums[i];
13
            }
14
            nums[i] = m;
15
            d = i+1;
16
            if (d < k) s = i+1;
17
            else if (d > k) e = i-1;
18
        } while (d != k);
19
        return nums[d-1];
20
    }
21
};





原创粉丝点击