码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 215. Kth Largest Element in an Array

时间:2016-07-09 19:16:14      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Problem: 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.

 

Thought:

Quick Sort partition

 

Code C++:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        if (k <= 0 || k > nums.size()) {
            return 0;
        }
        
        int q = partition(nums);
        if (q + 1 == k) {
            return nums[q];
        }
        vector<int>left;
        vector<int>right;
        for (int i = 0; i < q; i++) {
            left.push_back(nums[i]);
        }
        for (int i = q + 1; i < nums.size(); i++) {
            right.push_back(nums[i]);
        }
        
        if (q + 1 < k) {
            return findKthLargest(right, k - q -1);
        } else {
            return findKthLargest(left, k);
        }
        
    }
    
    int partition(vector<int>& nums){
        srand(unsigned(time(0)));
        int k = random() % nums.size();
        int key = nums[k];
        int temp = nums[k];
        nums[k] = nums.back();
        nums.back() = temp;
        int j = 0;
        for (int i = 0; i < nums.size() - 1; i++) {
            if (nums[i] > key) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                j++;
            }
        }
        temp = nums.back();
        nums.back() = nums[j];
        nums[j] = temp;
        return j;
    }
};

 

LeetCode 215. Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5656279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!