Wins the Offer-29. K minimum number (C ++ / Java)

topic:

Input n integers, find the smallest number K. 4,5,1,6,2,7,3,8 e.g. eight digital inputs, the minimum number is four 1,2,3,4 ,.

analysis:

First think of the array in ascending order, returns the first k elements. But then sorting efficiency may be lower, we can use the priority queue simulation heap to deal with.

Simulation of a maximum k elements stack, the stack when the number of elements equal to k when the new top of the stack elements and elements necessary to compare, if less than the top of the stack element, the top element of the stack is deleted, adding a new element into the heap, because the top of the heap biggest element is the largest element of the heap, we can keep the heap is the smallest element is always a few, because there are new elements to each, will be compared, the last element of the heap is the first k minimum the elements.

Spit slots, the final output of this problem and do not need to order the cattle off net sentenced question really lost.

program:

C++

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        if(input.size() == 0 || k == 0 || k > input.size())
            return res;
        for(int num:input){
            if(q.size() < k)
                q.push(num);
            else{
                if(num < q.top()){
                    q.pop();
                    q.push(num);
                }
            }
        }
        while(!q.empty()){
            res.push_back(q.top());
            q.pop();
        }
        //reverse(res.begin(), res.end());
        return res;
    }
private:
    vector<int> res;
    priority_queue<int> q;
};

Java

import java.util.*;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        if(input.length == 0 || k == 0 || k > input.length)
            return res;
        for(int num:input){
            if(queue.size() < k)
                queue.add(num);
            else{
                if(num < queue.peek()){
                    queue.poll();
                    queue.add(num);
                }
            }
        }
        for(Integer i : queue) {
            res.add(i);
        }
        return res;
    }
    static Comparator<Integer> cmp = new Comparator<Integer>() {
        public int compare(Integer e1, Integer e2) {
            return e2 - e1;
        }
    };
    private ArrayList<Integer> res = new ArrayList<>();
    private PriorityQueue<Integer> queue = new PriorityQueue<>(cmp);
}

 

Guess you like

Origin www.cnblogs.com/silentteller/p/11959368.html
Recommended