<LeetCode OJ> 215. Kth Largest Element in an Array

来源:互联网 发布:中国商发 知乎 编辑:程序博客网 时间:2024/05/05 14:40

在一个未排序的数组中找到第k大的元素,注意此言的第k大就是排序后的第k大的数,

注意:给定k总是安全有效的。

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.


解法1,直接排序:

排序后直接返回第k大的数,我估计没有人会看得起这种解法,time,o(n*lg(n)),space,o(1)

//思路首先://最笨的方法:排序,直接获取倒数第k个数class Solution {public:    int findKthLargest(vector<int>& nums, int k) {        sort(nums.begin(),nums.end());        return nums[nums.size()-k];    }};

为了提高锻炼编码,还是把快排默写一遍吧!

20ms的运行时间

class Solution {public:    //手动快速默写快排:先划界,再分治....    int quickPartion(vector<int>& nums,int low,int high)    {        int pos=rand()%(high-low+1)+low;        swap(nums,pos,high);//随机划界元        int key=nums[high];        int i=low-1;        for(int j=low;j<=high-1;j++)        {            if(nums[j]<=key)                swap(nums,++i,j);        }        swap(nums,++i,high);        return i;    }    void swap(vector<int> &nums,int i,int j)    {        int tmp=nums[i];        nums[i]=nums[j];        nums[j]=tmp;    }    void quickSort(vector<int> &nums,int low ,int high)    {        if(low<high)        {            int mid = quickPartion(nums,low ,high);            quickSort(nums,low,mid-1);            quickSort(nums,mid+1,high);        }    }    int findKthLargest(vector<int>& nums, int k) {        quickSort(nums,0,nums.size()-1);        return nums[nums.size()-k];    }};



解法2,快排划界:

总是将要划界的数组段末尾的元素为划界元,将比其小的数交换至前,比其大的数交换至后,最后将划界元放在“中间位置”(左边小,右边大)。划界将数组分解成两个子数组(可能为空)。

设数组下表从low开始,至high结束。
1、 总是取要划界的数组末尾元素为划界元x,开始划界:

a) 用j从low遍历到high-1(最后一个暂不处理),i=low-1,如果nums[j]比x小就将nums[++i]与nums[j]交换位置

b) 遍历完后再次将nums[i+1]与nums[high]交换位置(处理最后一个元素);

c) 返回划界元的位置i+1,下文称其为midpos

这时的midpos位置的元素,此时就是整个数组中第N-midpos大的元素,我们所要做的就像二分法一样找到K=N-midpos的“中间位置”,即midpos=N-K

2、 如果midpos==n-k,那么返回该值,这就是第k大的数。
3、 如果midpos>n-k,那么第k大的数在左半数组
4、 如果midpos<n-k,那么第k大的数在右半数组

//思路首先://快排划界,如果划界过程中当前划界元的中间位置就是k则找到了//time,o(n*lg(k)),space,o(1)class Solution {public:    //对数组vec,low到high的元素进行划界,并获取vec[high]的“中间位置”    int quickPartion(vector<int> &vec, int low,int high)    {      int x = vec[high];    int i = low - 1;    for (int j = low; j <= high - 1; j++)    {    if (vec[j] <= x)//小于x的划到左边    swap(vec,++i,j);    }    swap(vec,++i,high);//找到划界元的位置    return i;//返回位置    }     //交换数组元素i和j的位置    void swap(vector<int>& nums, int i, int j){          int temp = nums[i];          nums[i]=nums[j];          nums[j]=temp;      }     int getQuickSortK(vector<int> &vec, int low,int high, int k)      {          if(low >= high) return vec[low];    int  midpos = quickPartion(vec, low,high);   //对原数组vec[low]到vec[high]的元素进行划界      if (midpos == vec.size() - k)      //如果midpos==n-k,那么返回该值,这就是第k大的数      return vec[midpos];    else if (midpos < vec.size() - k)  //如果midpos<n-k,那么第k大的数在右半数组     return getQuickSortK(vec, midpos+1, high, k);        else                               //如果midpos>n-k,那么第k大的数在左半数组     return getQuickSortK(vec, low, midpos-1, k);    }     int findKthLargest(vector<int>& nums, int k) {        return getQuickSortK(nums,0,nums.size()-1,k);    }};


以下部分为别人家的算法.............参考讨论区,学习中....

解法3,最小堆

class Solution {public:        int findKthLargest(vector<int>& nums, int k) {        //if(nums.empty()) return         priority_queue<int,vector<int>,greater<int>> q;//use min heap         int count = 0;//firstly push the first k elements into the heap                int i=0;        while(i<k && i<nums.size())            q.push(nums[i++]);                    while(i<nums.size())        {            if(q.top()<nums[i])            {//if nums[i] is bigger, then delete the top and push a new value into the heap                q.pop();                q.push(nums[i]);            }            i++;        }        return q.top();    }};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50569555

原作者博客:http://blog.csdn.net/ebowtang

1 0