40 最小的K个数

package sort;

import java.util.Comparator;
import java.util.PriorityQueue;

public class Test40 {
    public static void main(String[] args) {
        int[] a = { 4, 5, 1, 6, 2, 7, 3, 8 };
        int k = 3;
        function(a, 5);
        for (int i = 0; i < 5; i++) {
            System.out.println(a[i]);
        }
    }

    public static PriorityQueue<Integer> function2(int[] a, int k) {

        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(
                new Comparator<Integer>() {//PriorityQueue默认为小顶堆,通过改写Comparator,改写成大顶对
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        // TODO Auto-generated method stub
                        return o2 > o1 ? 1 : (o2 == o1 ? 0 : -1);
                    }
                });

        for (int i = 0; i < a.length; i++) {
            if (i < k) {//前k个元素一次放入大顶对,
                queue.offer(a[i]);
            } else {//其他的元素需要与堆顶元素比较,大于堆顶则直接下一个,小于堆顶把原来的堆顶元素输出,添加新元素
                if (queue.peek() > a[i]) {
                    queue.remove();
                    queue.offer(a[i]);
                }

            }
        }

        return queue;

    }

    public static void function(int[] a, int k) {
        int low = 0;
        int high = a.length - 1;
        int index = position(a, low, high);//利用快排中的position函数,如果某次index=k-1,说明0-k-1都小于后面的数,
                                          //从而得到最小的k个数
        System.out.println("index:" + index);
        while (index != k - 1) {
            if (index < k - 1)
                index = position(a, index + 1, high);

            else
                index = position(a, low, index - 1);

        }

    }

    private static int position(int[] a, int low, int high) {//相当于快排的单步计算
        // TODO Auto-generated method stub
        int l = low;
        int h = high;
        int temp = a[l];
        while (l < h) {

            while (l < h && a[h] > temp) {
                h--;
            }
            if (l < h)
                a[l++] = a[h];
            while (l < h && a[l] < temp) {
                l++;
            }
            if (l < h)
                a[h--] = a[l];

        }
        a[l] = temp;

        return l;
    }
}
 

发布了41 篇原创文章 · 获赞 1 · 访问量 750

猜你喜欢

转载自blog.csdn.net/coder_my_lover/article/details/105305482