题目描述:给定一个数组,数组的中的元素是无序的,找出其中第K大的数。
解决办法:对于数组直接对数组进行排序,找到第K大的数,对于链表,先转化为数组然后求第K大的数。java示例代码如下:
import java.util.*;
public class FindKth{
public static void main(String[] args)
{
//For the case of array
int [] n={1,23,12,12,12,58,24,44,32,56,56,56,67,23,44};
getKth(n,5);
//For the case of list
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 1);
list.add(1, 23);
list.add(2,12);
list.add(3,58);
list.add(4,24);
list.add(5,44);
int [] array = new int[list.size()];
for(int i=0;i<list.size();i++)
{
array[i]=(Integer) list.get(i);
}
getKth(array,5);
}
//The method to find the kth number
private static void getKth(int [] a,int k)
{
Arrays.sort(a);
int count=0;
for(int x =a.length-1;x>=0;x--)
{
if(a[x-1]!=a[x])
{
count++;
if(count==k)
{
System.out.println("The "+k+"th number is:"+a[x]);
break;
}
}
}
}
}
运行结果得到:The 5th number is 32
The 5th number is 12