【堆】最小的K个数

输入n个整数,找出其中最小的K个数

 

解法一:

public static List getMinKNum(int[] input, int k) {
	if(null == input || input.length == 0 || k <= 0){
		return null;
	}

	PriorityQueue list = new PriorityQueue(new Comparator(){
		@Override
		public int compare(Integer o1, Integer o2){
            //倒序
			return o2 - o1;
		}
	});

	for(int i = 0; i < input.length; i++){
		if(list.size() == k && list.peek() < input[i]){
			continue;
		}
		if(list.size() == k){
			list.poll();
		}
		list.offer(input[i]);
	}

	List result = new ArrayList();
	Iterator iterator = list.iterator();
	while(iterator.hasNext()){
		result.add(iterator.next());
	}

	return result;
}

解法二:



import java.util.ArrayList;
import java.lang.Integer;

/**
 * @author Joeson Chan
 */
public class GetMinKNum{

    public static ArrayList getMinKNum(int [] input, int k) {
        if(k == 0 || null == input || input.length == 0 || k > input.length){
            return new ArrayList();
        }

        ArrayList result = new ArrayList();
        for(int i = 0; i < input.length; i++){
            if(result.size() < k){
                up(result, input[i]);
            }else{
                down(result, k, input[i]);
            }
        }

        return result;
    }

    private static void up(ArrayList result, int value){
        result.add(value);
        int offset = result.size() - 1;
        while(offset > 0){
            int parent = (offset - 1) / 2;
            if(result.get(parent) < value){
                swap(result, parent, offset);
            }
            offset = parent;
        }
    }

    private static void down(ArrayList result, int k, int value){
        if(result.size() == k && value > result.get(0)){
            return;
        }

        result.set(0, value);
        int offset = 0;
        while(offset < result.size()){
            int child = (offset * 2) + 1;
            if(child < result.size() - 1 && result.get(child) < result.get(child + 1)){
                child++;
            }
            if(child < result.size() && result.get(child) > value){
                swap(result, offset, child);
            }

            offset = child;
        }
    }
    
    private static void swap(ArrayList result, int index1, int index2){
        int tmp = result.get(index1);
        result.set(index1, result.get(index2));
        result.set(index2, tmp);
    }
    
    
}

 

你可能感兴趣的:(算法题)