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

Leetcode题解(3):L215/Kth Largest Element in an Array

时间:2015-06-07 09:40:21      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:leetcode   quick-sort   array   

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

解题思路:可用快排方法求解,在实际生活中,一般需求在变,需要多次查询不同的大数或小数,这种情况下,还是先将整个数组排序,一劳永逸

class Solution {
public:
    void swap(int& d1, int&d2){
        int tmp = d1;
        d1 = d2;
        d2 = tmp;       
    }

    int partion(vector<int>& nums, int low, int high){
        int i = low+1;
        int j = high;
        while(i<=j)
        {
            while(i<=high && nums[i]<=nums[low])
                i++;
            while(j>low && nums[j]>=nums[low])
                j--;
            if(i<j)
                swap(nums[i],nums[j]);
        }
        swap(nums[low],nums[j]);
        return j;
    }

    int findKthLargest(vector<int>& nums, int k) {
        int low = 0;
        int size = nums.size();
        int high = size - 1;
        k = size - k; 

        int parti;
        while(low<=high)
        {
            parti = partion(nums, low, high);
            if(parti == k)
                return nums[parti];
            if(parti < k)
                low = parti + 1;
            else
                high = parti - 1;
        }
    }
};

Leetcode题解(3):L215/Kth Largest Element in an Array

标签:leetcode   quick-sort   array   

原文地址:http://blog.csdn.net/kzq_qmi/article/details/46391571

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