#5 Kth Largest Element

题目描述:

Find K-th largest element in an array.

 Notice

You can swap elements in the array

Example

In array [9,3,2,4,8], the 3rd largest element is 4.

In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4, 3rd largest element is 3 and etc.

Challenge 

O(n) time, O(1) extra memory.

题目思路:

这题要达到题目要求,只能用quick sort的思想:不断找pivot,如果它在第k个位置,就返回nums[k - 1];不然就根据pivot的位置进行recursive查找。

Mycode(AC = 82ms):

class Solution {
public:
    /*
     * param k : description of k
     * param nums : description of array and index 0 ~ n-1
     * return: description of return
     */
    int kthLargestElement(int k, vector<int> nums) {
        // write your code here
        if (nums.size() == 0) return 0;
        
        kthLargestElement(k, nums, 0, nums.size() - 1);
        return nums[k - 1];
    }
    
    void kthLargestElement(int& k,
                           vector<int>& nums,
                           int start,
                           int end)
    {
        if (start >= end) return;
        
        int pivot = findPivot(nums, start, end);
        if (pivot > k) {
            kthLargestElement(k, nums, start, pivot - 1);
        }
        else if (pivot < k) {
            kthLargestElement(k, nums, pivot + 1, end);
        }
        else {
            return;
        }
    }
    
    int findPivot(vector<int>& nums, int start, int end) {
        if (start == end) return start;
        
        int pivot = nums[end];
        int l = start, r = end;
        while (l < r) {
            while (l < r && nums[l] >= pivot) {
                l++;
            } 
            nums[r] = nums[l];
            
            while (l < r && nums[r] <= pivot) {
                r--;
            }
            nums[l] = nums[r];
        }
        
        nums[l] = pivot;
        return l;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值