此题其实是考排序,在之初用冒泡排序超出运行时间,所以用快速排序,顺利AC
题目如下:
-
题目描述:
-
浙江桐乡乌镇共有n个人,请找出该镇上的前m个大富翁.
-
输入:
-
输入包含多组测试用例.
每个用例首先包含2个整数n(0<n<=100000)和m(0<m<=10),其中: n为镇上的人数,m为需要找出的大富翁数, 接下来一行输入镇上n个人的财富值.
n和m同时为0时表示输入结束.
-
输出:
-
请输出乌镇前m个大富翁的财产数,财产多的排前面,如果大富翁不足m个,则全部输出,每组输出占一行.
-
样例输入:
-
3 1 2 5 -1 5 3 1 2 3 4 5 0 0
-
样例输出:
-
5 5 4 3
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
int n = cin.nextInt();
int m = cin.nextInt();
if (n == 0 && m == 0)
break;
int[] a = new int[n];
for (int i = 0; i < n; i ++) {
a[i] = cin.nextInt();
}
if (n < m) {
for (int i = 0; i < n; i ++) {
if (i != n - 1)
System.out.print(a[i] + " ");
else
System.out.print(a[i]);
}
}
else {
quickSort(a, 0, a.length - 1);
for (int i = 0; i < m; i ++) {
if (i != m - 1) {
System.out.print(a[i] + " ");
}
else
System.out.print(a[i] + "\n");
}
}
}
}
//快速排序
private static void quickSort(int[] array, int from, int to) {
if (from < to) {
int temp = array[to];
int i = from - 1;
for (int j = from; j < to; j++) {
if (array[j] >= temp) {
i++;
int tempValue = array[j];
array[j] = array[i];
array[i] = tempValue;
}
}
array[to] = array[i+1];
array[i+1] = temp;
quickSort(array, from, i);
quickSort(array, i + 1, to);
}
}
}
/**************************************************************
Problem: 1034
User: mchenyuxiang
Language: Java
Result: Accepted
Time:1370 ms
Memory:81784 kb
****************************************************************/