第K大的数

来源:互联网 发布:php nodejs 编辑:程序博客网 时间:2024/04/30 13:08

在数组中找到第k大的元素

 注意事项

你可以交换数组中的元素的位置


样例

给出数组 [9,3,2,4,8],第三大的元素是 4

给出数组 [1,2,3,4,5],第一大的元素是 5,第二大的元素是 4,第三大的元素是 3,以此类推


import java.util.Scanner;/** *  * 第k大的数 * @author Dell * */public class Test4 {   public static int patition(int[] a, int low, int high)   {     int temp=a[low];   int i=low;   int j=high;   while(i<j)   {   while(i<j&&a[j]<temp) j--;   if(i<j)   {   a[i]=a[j];   i++;   }   while(i<j&&a[i]>temp) i++;   if(i<j)   {   a[j]=a[i];   j--;   }   a[i]=temp;      }   return i;      }   public static int solution(int[] a,int k)   {     int start=0;   int end =a.length-1;   int index=patition(a,start,end);   while(index!=k-1)   {   if(index>k-1)   {   end=index-1;    index=patition(a,start,end);   }   else   {   start=index+1;   index=patition(a,start,end);    }      }   return  a[index];      }public static void main(String[] args) {Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int []a=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); }      System.out.println(solution(a,k));  }}







原创粉丝点击