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

时间:2015-06-07 09:38:57   收藏:0   阅读:240

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;
        }
    }
};

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!