leetcode 215: Kth Largest Element in an Array

Use quick sort.

This is the 8ms version. With the sorting of the whole array, the time is long.

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n=nums.size();
        quicksort(nums,0,n-1);
        return nums[k-1];
    }
    void quicksort(vector<int>& nums,int L,int R)
    {
        int l=L,r=R;
        int key=nums[l];
        while(l<r)
        {
            while(l<r&&nums[r]<key)
                r--;
            nums[l]=nums[r];
            while(l<r&&nums[l]>=key)
                l++;
            nums[r]=nums[l];
        }
        nums[l]=key;
        if(l-1>L)
            quicksort(nums,L,l-1);
        if(l+1<R)
            quicksort(nums,l+1,R);
    }
};

This is the 4ms version, I learned it from http://www.cnblogs.com/easonliu/p/4523941.html. It does not sort the whole array to find the number. Just sort the correct range is ok.

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n=nums.size();
        int L=0,R=n-1;
        while (L<R) {
            int l=L,r=R;
            int key=nums[l];
            while (l<r) {
                while (l<r&&nums[r]<key)
                    r--;
                nums[l]=nums[r];
                while (l<r&&nums[l]>=key)
                    l++;
                nums[r]=nums[l];
            }
            nums[l]=key;
            //do not have to sort the whole array, just sort the range with k-1 inside
            if (l==k-1) return nums[k - 1];
            else if (l>k-1) R=l-1;
            else L=l+1;
        }
        return nums[k-1];
    }
};


發佈了186 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章