第K大问题

1. 输入n个整数,输出其中最小的k个。

  堆做法、quickSelect做法。

堆做法代码:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

public class Solution {

    public List<Integer> getKSmallest(int[] a, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return b.compareTo(a);
            }
        });
        int n = a.length;
        for (int i = 0; i < k; i++)
            pq.add(a[i]);

        for (int i = k; i < n; i++) {
            if (a[i] < pq.peek()) {
                pq.remove();
                pq.add(a[i]);
            }

        }
        List<Integer> res = new ArrayList<Integer>();
        for (Integer each : pq)
            res.add(each);

        return res;
    }

    public static void main(String[] args) {
        int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 };
        System.out.println(new Solution().getKSmallest(a, 3));

    }
}
View Code

 

2、谷歌面试题:输入是两个整数数组,他们任意两个数的和又可以组成一个数组,求这个和中前k个数怎么做。

 

 

参考:

http://taop.marchtea.com/02.01.html

http://www.51nod.com/question/index.html#!questionId=46

posted @ 2014-09-30 09:59  jdflyfly  阅读(199)  评论(0编辑  收藏  举报