剑指offer-- 第40题 最小的k个数

第40题 最小的k个数

题目 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路 最直观的是先排序,在获取前k个数。
自己写的Low代码

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (input == null || input.length < k) {
            return list;
        }
        // 排序;
        for (int i = 0; i < input.length; i++) {
            for (int j = 0; j+1 < input.length - i; j++) {
                if (input[j] > input[j + 1]) {
                    int temp = input[j];
                    input[j] = input[j + 1];
                    input[j + 1] = temp;
                }
            }
        }
        for(int i=0;i<k;i++) {
            list.add(input[i]);
        }
        return list;
    }
}

猜你喜欢

转载自www.cnblogs.com/LynnMin/p/9296742.html