例题:
输入 N(N<=100)个数,每个数的范围> 0 并且 <= 100,请将每个不同的数从小到大输出并且输出它对应的个数。
样例输入:
8
3 2 2 1 1 4 5 5
样例输出:
1 2
2 2
3 1
4 1
5 2
代码如下:
package com.yt.noobdream;
import java.util.Scanner;
public class ArrayUse01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();//控制输入几个数字
int[] a = new int[n];
for (int i = 0; i < n; i++) {
int j = scanner.nextInt();
if (j < n) {
a[j]++;
} else {
System.out.println("输入的数太大");
}
}
for (int i = 0; i < n; i++) {
if (a[i] > 0) {
System.out.printf("值%d 有 %d个\n",i,a[i]);
}
}
}
}
改进例题:
输入 N(N<=100)个数,每个数的范围> 0 并且 <= 100,请将每个不同的数输出并且输出它对应的个数。要求按值出现的次数从小到大排序,如果多个值有相同的个数,只用输出值最大的那个。
样例输入:
8
3 2 2 1 1 4 5 5
样例输出:
4 1
5 2
代码实现:
package com.yt.noobdream;
import java.util.Scanner;
public class ArrayUse01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();//控制输入几个数字
int[] a = new int[n];
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
int j = scanner.nextInt();
if (j < n) {
a[j]++;//将输入的值作为数组的下标,每一次有相同的值输入就让个数增加
} else {
System.out.println("输入的数太大");
}
}
for (int i = 0; i < n; i++){
temp[a[i]] = i;//a[i]表示下标i的个数,下标i表示当前最大值
}
for (int i = 1; i < n; i++) {
if (temp[i] > 0) {
System.out.printf("最大值=%d ,个数=%d\n",temp[i],i);
}
}
}
}