关于java:JZ029最小的-K-个数

24次阅读

共计 934 个字符,预计需要花费 3 分钟才能阅读完成。

题目

最小的 K 个数

输出 n 个整数,找出其中最小的 K 个数。例如输出 4,5,1,6,2,7,3,8 这 8 个数字,则最小的 4 个数字是 1,2,3,4。

题目链接 : 最小的 K 个数

代码

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 题目:最小的 K 个数
 * 题目形容
 * 输出 n 个整数,找出其中最小的 K 个数。例如输出 4,5,1,6,2,7,3,8 这 8 个数字,则最小的 4 个数字是 1,2,3,4。* 题目链接:* https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&&tqId=11182&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz29 {public ArrayList<Integer> getLeastNumbers_Solution(int[] input, int k) {ArrayList<Integer> result = new ArrayList<Integer>();
        if (input == null) {return result;}
        if (k > input.length) {return result;}
        Arrays.sort(input);
        for (int i = 0; i < k; i++) {if (i < input.length) {result.add(input[i]);
            }
        }
        return result;
    }

    public static void main(String[] args) {Jz29 jz29 = new Jz29();
        int[] input = new int[]{4, 5, 1, 6, 2, 7, 3, 8};
        ArrayList<Integer> result = jz29.getLeastNumbers_Solution(input, 10);
        for (Integer data : result) {System.out.println(data);
        }
    }
}

【每日寄语】生存总是这样,不能叫人处处称心,但咱们还要激情活下去。人活毕生,值得爱的货色很多,不要因为一个不称心就灰心。

正文完
 0