leetcode--Kth Largest Element in an Array

来源:互联网 发布:iis url重写 端口号 编辑:程序博客网 时间:2024/06/05 23:08

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.

[java] view plain copy
  1. public class Solution {  
  2.     public int findKthLargest(int[] nums, int k) {  
  3.         if(k>nums.length) return 0;  
  4.         int mid = partion(nums, 0, nums.length-1);  
  5.         while(mid!=k-1){  
  6.             if(mid>k-1){  
  7.                 mid = partion(nums, 0, mid-1);  
  8.             }else{  
  9.                 mid = partion(nums, mid+1, nums.length-1);  
  10.             }  
  11.         }  
  12.         return nums[mid];  
  13.     }  
  14.           
  15.     int partion(int[] nums,int start,int end){  
  16.         int t = nums[start];  
  17.         while(start<end){  
  18.             while(start<end&&nums[end]<=t){  
  19.                 end--;  
  20.             }  
  21.             nums[start] = nums[end];  
  22.             while(start<end&&nums[start]>=t){  
  23.                 start++;  
  24.             }  
  25.             nums[end] = nums[start];  
  26.         }  
  27.         nums[start] = t;  
  28.         return start;  
  29.     }  
  30. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46581419

原创粉丝点击