1,问题描述
试题编号: | 201503-2 |
试题名称: | 数字排序 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: |
问题描述
给定
n个整数,请统计出每个整数出现的次数,按出现次数从多到少的顺序输出。
输入格式
输入的第一行包含一个整数
n,表示给定数字的个数。
第二行包含 n个整数,相邻的整数之间用一个空格分隔,表示所给定的整数。
输出格式
输出多行,每行包含两个整数,分别表示一个给定的整数和它出现的次数。按出现次数递减的顺序输出。如果两个整数出现的次数一样多,则先输出值较小的,然后输出值较大的。
样例输入
12
5 2 3 3 1 3 4 2 5 2 3 5
样例输出
3 4
2 3 5 3 1 1 4 1
评测用例规模与约定
1 ≤
n ≤ 1000,给出的数都是不超过1000的非负整数。
|
2,代码:
(100分答案)
思路: 首先,记录每个数字出现的次数,并把该数字和它出现的次数存到一个数组(result)中。
用HashMap 得到(输入的数组中,不同数字的个数)
然后,分两步。(1),次数排序,把result数组按照次数降序排序。(2),大小排序,把次数相同的数字按照升序排序。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
Map map = new HashMap();
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
map.put(arr[i], i);
}
// 数组中不同的数 map.size()
//存放结果
int[][] result = new int[map.size()][2];
int resulti = 0;
//记录次数
int count = 0;
for(int i=0;i<n;i++){
count = 0;
for(int j=0;j<n;j++){
if(arr[i] > 0 && arr[i] == arr[j]){
count ++;
}
}
if(arr[i] > 0){
result[resulti][0] = arr[i];
result[resulti][1] = count;
resulti ++;
}
//负值标记
for(int j=0;j<n;j++){
if(arr[j] > 0 && Math.abs(arr[i]) == Math.abs(arr[j])){
arr[j] = -arr[j];
}
}
}
// 排序
int temp1 = 0;
int temp2 = 0;
for(int i=0;i<map.size();i++){
for(int j=0;j<map.size();j++){
if(result[j][1] < result[i][1]){
temp1 = result[i][0];
temp2 = result[i][1];
result[i][0] = result[j][0];
result[i][1] = result[j][1];
result[j][0] = temp1;
result[j][1] = temp2;
}
}
}
//次数一样多 - 处理
int same = 1;
int sameTemp = 0;
int sameChange = 0;
for(int i=0;i<map.size()-1;i++){
if(result[i][1] == result[i+1][1]){
same ++;
}else{
same = 1;
}
if(same > 1){
sameTemp = 0;
while( sameTemp != same-1){
if(result[i-sameTemp][0] > result[i+1-sameTemp][0]){
sameChange = result[i-sameTemp][0];
result[i-sameTemp][0] = result[i+1-sameTemp][0];
result[i+1-sameTemp][0] = sameChange;
}
sameTemp ++;
}
}
}
for(int i=0;i<map.size();i++){
for(int j=0;j<2;j++){
if(result[i][j] != 0){
System.out.print(result[i][j]+" ");
}
}
System.out.println();
}
}
}