题目1431:Sort(哈希算法)

来源:互联网 发布:java短信接口代码实例 编辑:程序博客网 时间:2024/05/16 07:14

时间限制:1 秒

内存限制:128 兆

特殊判题:

提交:3156

解决:1083

题目描述:

给你n个整数,请按从大到小的顺序输出其中前m大的数。

输入:

每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。

输出:

对每组测试数据按从大到小的顺序输出前m大的数。


该题如果用直接排序的方式解决的话满足不了内存要求,10000000 个整型的存储会超过题目要求所需内存限制。

样例输入:
5 33 -35 92 213 -644
样例输出:
213 92 3
import java.util.Scanner; public class Main{     /**     * @param args     */    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);                 while( scanner.hasNext() ){            int n = scanner.nextInt();            int m = scanner.nextInt();            int hash[] = new int[1000001];            for (int i = 0; i < n; i++) {                int value = scanner.nextInt();                hash[value+500000]++;            }            for (int i = hash.length - 1; i >= 0 && m > 0; i--) {                if(hash[i] != 0){                    if(m == 1){                        System.out.println(i - 500000);                        hash[i]--;                        m--;                    }else{                        System.out.print(i - 500000 + " ");                        hash[i]--;                        m--;                    }                }                             }        }    } } /**************************************************************    Problem: 1431    User: yihukurama    Language: Java    Result: Accepted    Time:2690 ms    Memory:223828 kb****************************************************************/


0 0
原创粉丝点击