加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

求数组中的K大数(时间复杂度控制…

发布时间:2020-12-14 04:01:26 所属栏目:大数据 来源:网络整理
导读:【源码】 package cn.edu.nwsuaf.cie.qhs; import java.util.Random; import java.util.Scanner; public class GetGreateK { ? ? ? private int initArray[]; ? ? ? public int[] getInitArray() { ? ? ? ? ? ? return initArray; ? ? ? } ? ? ? public void
【源码】 package cn.edu.nwsuaf.cie.qhs; import java.util.Random; import java.util.Scanner; public class GetGreateK { ? ? ? private int initArray[]; ? ? ? public int[] getInitArray() { ? ? ? ? ? ? return initArray; ? ? ? } ? ? ? public void setInitArray(int[] initArray) { ? ? ? ? ? ? this.initArray = initArray; ? ? ? } ? ? ? public GetGreateK(){} ? ? ? public GetGreateK(int[] array){ ? ? ? ? ? ? this.initArray = array; ? ? ? } ? ? ? public int random_partion(int start,int length){ ? ? ? ? ? ? Random rand = new Random(); ? ? ? ? ? ? int index = rand.nextInt(length); ? ? ? ? ? ? int i = start-1; ? ? ? ? ? ? int j = start; ? ? ? ? ? ? this.swap(index,length-1); ? ? ? ? ? ? for(j=start;j<length;j++){ ? ? ? ? ? ? ? ? ? if(initArray[j] < initArray[length-1]){ ? ? ? ? ? ? ? ? ? ? ? ? this.swap(++i,j); ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? this.swap(++i,length-1); //? ? ? ? ? ? System.out.println("------>"+i); ? ? ? ? ? ? return i; ? ? ? } ? ? ? public int getMaxK(int start,int length,int k){ ? ? ? ? ? ? int mid; ? ? ? ? ? ? if (k<=0) return -1; ? ? ? ? ? ? if (length<k) return -1; ? ? ? ? ? ? mid = this.random_partion(start,length); ? ? ? ? ? ? if (mid == length-k) return initArray[mid]; ? ? ? ? ? ? else if(mid < length-k) return getMaxK(start+mid+1,length-mid-1,k); ? ? ? ? ? ? else return getMaxK(start,mid,k-(length-mid)); ? ? ? } ? ? ? ? ? ? public void swap(int a,int b){ ? ? ? ? ? ? int temp = initArray[a]; ? ? ? ? ? ? initArray[a] = initArray[b]; ? ? ? ? ? ? initArray[b] = temp; ? ? ? } ? ? ? ? ? ? public static void main(String[] args) { ? ? ? ? ? ? // TODO Auto-generated method stub ? ? ? ? ? ? //12012? 3? 945? 965? 66? 232? 65? 7? 8? 898? 56? 878? 170? 13? 5 ? ? ? ? ? ? int[] array; ? ? ? ? ? ? int length; ? ? ? ? ? ? int K; ? ? ? ? ? ? Scanner scanner = new Scanner(System.in); ? ? ? ? ? ? System.out.println("请输入数组长度:"); ? ? ? ? ? ? length = scanner.nextInt(); ? ? ? ? ? ? array = new int[length]; ? ? ? ? ? ? for(int i = 0; i < length;i++){ ? ? ? ? ? ? ? ? ? System.out.println("请输入第"+(i+1)+"个数:"); ? ? ? ? ? ? ? ? ? array[i] = scanner.nextInt(); ? ? ? ? ? ? } ? ? ? ? ? ? System.out.println("请输入K:"); ? ? ? ? ? ? K = scanner.nextInt(); ? ? ? ? ? ? GetGreateK kth = new GetGreateK(); ? ? ? ? ? ? kth.setInitArray(array); ? ? ? ? ? ? int maxK = kth.getMaxK(0,array.length,K); ? ? ? ? ? ? System.out.println("maxK---->"+maxK); ? ? ? } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读