4

JZ-029-最小的 K 个数

 2 years ago
source link: https://segmentfault.com/a/1190000041139017
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JZ-029-最小的 K 个数

发布于 12 月 18 日

最小的 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);
        }
    }
}

【每日寄语】 生活总是这样,不能叫人处处满意,但我们还要热情活下去。人活一生,值得爱的东西很多,不要因为一个不满意就灰心。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK