【每天学点算法题10.18】找出数组中的第K大的数

本文介绍了一种通过排序数组来找到数组中第K大数值的方法,并提供了Java实现示例代码。该方法适用于数组和链表两种数据结构。

题目描述:给定一个数组,数组的中的元素是无序的,找出其中第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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值