Leetcode215: Kth Largest Element in an Array

来源:互联网 发布:体育数据 编辑:程序博客网 时间:2024/05/17 07:38

215. 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.

题意:

找出一个数组中第K大的元素。

解答①:

这一题和之前做过的一个找出第K小的元素的题目相似哦,从那一题中我学到了用优先队列来做,所以看到这一题我第一个想法就是利用优先队列。同时,利用优先队列找出第K大的元素比找出第K小的元素更加简便。

本题只需要遍历一遍数组,将元素全部添加到队列中,这样的话来建立一个堆。然后根据其性质,将前K-1个元素全部弹出,剩下的处于队列最前面的元素就是需要寻找的第K大的元素。

代码:[cpp] view plain

  1. class Solution {  
  2. public:  
  3.     int findKthLargest(vector<int>& nums, int k) {  
  4.         priority_queue<int,vector<int> >q;  
  5.         for(int i=0;i<nums.size();i++)  
  6.         q.emplace(nums[i]);  
  7.         for(int j=0;j<k-1;j++) q.pop();  
  8.         return q.top();  
  9.     }  
  10. };  
复杂度:

建立堆的时间复杂度是O(n),然后pop的时间复杂度是O(logn),所以总的时间复杂度是O(n)。

解答②:

因为这道题目有一个tag是分治算法,而且这道题有一个典型的解法是利用快排的思想。

选中数组中的一个值作为pivot,然后将小于pivot的数字放在pivot的右边,将大于等于pivot的数字放在其左边。接着判断两边数字的数量,如果左边的个数小于K个,说明第K大的数字在pivot以及pivot右边的区域里面,接着对pivot的右边进行该利用快排思想的操作。要是右边的数量小于K个,说明第K大的数字在pivot以及pivot左边的区域里面,这时对pivot左边执行快排思想的操作。一直到左区域刚好有K-1个数,那么此时的pivot就是第K大的数。
代码:
[cpp] view plain

  1. class Solution {  
  2. public:  
  3.     int findKthLargest(vector<int>& nums, int k) {  
  4.         int high=nums.size();  
  5.         int low=0;  
  6.         while(low<high){  
  7.             int x=low,y=high-1;  
  8.             int pivot=nums[low];  
  9.             while(x<=y){  
  10.                 while(x<=y && nums[x]>=pivot) x++;  
  11.                 while(x<=y && nums[y]<pivot)  y--;  
  12.                 if(x<y) swap(nums[x++],nums[y--]);  
  13.             }  
  14.             swap(nums[low],nums[y]);  
  15.             if(y==k-1) return nums[y];  
  16.             else if(y<k-1) low=y+1;  
  17.             else high=y;  
  18.         }  
  19.     }  
  20. };  
复杂度:

利用快速排序的思想求第K大的数字的时间复杂度是O(n)。

0 0
原创粉丝点击