最小的k个数

发布时间:2022-06-21 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了最小的k个数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

1.常规解法

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        Arrays.sort(arr);
        int len=arr.length;
        int[] a=new int[k];
        int t=0;
        for(int i=0;i<k;i++)
        {
            a[t++]=arr[i];

        }
        return a;

    }
}

 

 

2.快速排序法

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        quicksort(arr,0,arr.length-1);
        return Arrays.copyOf(arr,k);
       
    }

    public void quickSort(int[] arr,int low,int high){
        if(low>=high)return;
        int pivotPos=partITion(arr,low,high);
        quickSort(arr,low,pivotPos-1);
        quickSort(arr,pivotPos+1,high);



    }

    int partition(int[] arr,int low,int high){
        int pivot=arr[low];
        while(low<high)
        {
            while(low<high&&arr[high]>=pivot)high--;
            arr[low]=arr[high];
            while(low<high&amp;&arr[low]<=pivot)low++;
            arr[high]=arr[low];


        }
        arr[low]=pivot;
        return low;



    }
}

 

脚本宝典总结

以上是脚本宝典为你收集整理的最小的k个数全部内容,希望文章能够帮你解决最小的k个数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。