n 个数里最小的 k 个

题目描述:找出n个数里最小的k个

输入描述:每个测试输入包含空格分割的n+1个整数,最后一个整数为k值,n 不超过100。

输出描述:输出n个整数里最小的k个数。升序输出

示例

输入

3 9 6 8 -10 7 -11 19 30 12 23 5

输出

-11 -10 3 6 7

一般思路:每次通过比较在数组中找出最小的数与前面的数交换并输出。

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s = sc.nextLine();
            String[] str = s.split(" ");
            int k = Integer.parseInt(str[str.length - 1]);
            int i = 0;
            while(i < k){
                int min = i;
                for(int j = min + 1;j < str.length - 2;j++){
                    if(Integer.parseInt(str[min]) > Integer.parseInt(str[j])){
                        min = j;
                    }
                }
                String tmp = str[i];
                str[i] = str[min];
                str[min] = tmp;
                if(i == (k - 1)){
                    System.out.print(str[i]);
                }else{
                    System.out.print(str[i]+" ");
                }
                i++;
            }
        }
    }
}

快排的思想:排序+分区。找到下标为k的位置,则可知,前k小的都在左边,排序输出即可

import java.util.*;
public class Main{
    private static int partition(int[] a,int begin,int end){
        int pivot = a[begin];
        int i = begin,j = end;
        while(i < j){
            while(i < j && a[j] >= pivot){
                j--;
            }
            a[i] = a[j];
            while (i < j && a[i] < pivot){
                i++;
            }
            a[j] = a[i];
        }
        a[i] = pivot;
        return i;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s = sc.nextLine();
            String[] str = s.split(" ");
            int k = Integer.parseInt(str[str.length - 1])-1;
            int[] arr = new int[str.length - 1];
            for(int i = 0;i < arr.length;i++){
                arr[i] = Integer.parseInt(str[i]);
            }
            int start = 0;
            int end = arr.length - 1;
            int index = partition(arr,start,end);
            while(index != k){
                if(index > k){
                    end = index - 1;
                    index = partition(arr,start,end);
                }else{
                    start = index + 1;
                    index = partition(arr,start,end);
                }
            }
            Arrays.sort(arr,0,index);
            for(int i = 0;i <= k;i++){
                System.out.print(i==k ? arr[i] : (arr[i]+" "));
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值