剑指Offer-1.19-40

在这里插入图片描述
方法一:

class Solution {
    
    
    public int[] getLeastNumbers(int[] arr, int k) {
    
    
        Arrays.sort(arr);
        int[]  res = new int[k];
        for (int i = 0; i < k; i++) {
    
    
            res[i] = arr[i];
        }
        return res;
    }
}

方法二:
提示:利用大根堆,先创建一个包含 k 个节点的大根堆(利用 PriorityQueue 实现),然后遍历后面的节点,如果比大根堆的根小,就将大根堆的根去除,加入当前节点,遍历完后,大根堆里面的节点就是最小的 k 个元素

class Solution {
    
    
    public int[] getLeastNumbers(int[] arr, int k) {
    
    
        int[] res = new int[k];
        if (k == 0) {
    
    
            return res;
        }
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>(){
    
    
            public int compare(Integer o1, Integer o2) {
    
    
                return o2 - o1;
            }
        });
        for (int i = 0; i < k; i++) {
    
    
            queue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
    
    
            if (arr[i] < queue.peek()) {
    
    
                queue.poll();
                queue.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; i++) {
    
    
            res[i] = queue.poll();
        }
        return res;
    }
}

注意:PriorityQueue 默认实现的是按照从小到大的顺序(小根堆),所以要实现从大到小的顺序(大根堆)就需要在里面传入一个比较器对象来控制顺序。

方法三:
快排:

class Solution {
    
    
    public int partition(int[] arr, int start, int end) {
    
    
        int base = arr[start];
        while (start < end) {
    
    
            while (start < end && arr[end] >= base) {
    
    
                end--;
            }
            if (start < end) {
    
    
                arr[start] = arr[end];
            }
            while (start < end && arr[start] <= base) {
    
    
                start++;
            }
            if (start < end) {
    
    
                arr[end] = arr[start];
            }
        }
        arr[start] = base;
        return start;
    }

    public void quickSort(int[] arr, int start, int end, int k) {
    
    
        int m = partition(arr, start, end);
        if (m == k) {
    
    
            return;
        } else if (m < k) {
    
    
            quickSort(arr, m + 1, end, k);
        } else {
    
    
            quickSort(arr, start, m - 1, k);
        }
    }

    public int[] getLeastNumbers(int[] arr, int k) {
    
    
        int[] res = new int[k];
        if (k == 0) {
    
    
            return res;
        }
        quickSort(arr, 0, arr.length - 1, k - 1);
        for (int i = 0; i < k; i++) {
    
    
            res[i] = arr[i];
        }
        return res;
    }
}

注意:快排得模板写法

猜你喜欢

转载自blog.csdn.net/Desperate_gh/article/details/112811123
今日推荐