两种解法:第一种较为简单,第二种要看知识点哦~
问题描述
在一个有限的正整数序列中,有些数会多次重复出现在这个序列中。
如序列:3,1,2,1,5,1,2。其中1就出现3次,2出现2次,3出现1 次,5出现1次。
你的任务是对于给定的正整数序列,从小到大依次输出序列中出现的数及出现的次数。
输入格式
第一行正整数n,表示给定序列中正整数的个数。
第二行是n 个用空格隔开的正整数x,代表给定的序列。
输出格式
若干行,每行两个用一个空格隔开的数,第一个是数列中出现的数,第二个是该数在序列中出现的次数。
样例输入
12
8 2 8 2 2 11 1 1 8 1 13 13
样例输出
1 3
2 3
8 3
11 1
13 2
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
Arrays.sort(arr); // 排序
HashSet<Integer> set = new HashSet<Integer>(); // 去重集合
int ans = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
ans++;
}
}
if (!set.add(arr[i])) { // 不等于arr数组重复值
ans = 0;
continue; // 跳出循环
} else {
System.out.println(i + " " + ans); // 输出,还有换行
System.out.println();
ans = 0;
}
}
}
知识点:与SortedSet接口类似,SortedMap也是一个结构,待排序的Map,其一个比较常用的实现类是TreeMap。
TreeMap的put(K key, V value)方法在每添加一个元素时,都会自动排序。
treemap()使用键的自然顺序构造一个新的、空的树映射.树状图(比较器<?)(超级K>比较器)构造一个新的、空的树映射,该映射根据给定比较器进行排序。树状图(地图<?)扩展K?扩展V>m)构造一个与给定映射具有相同映射关系的新的树映射,该映射根据其键的自然顺序进行排序。
详情指路:https://www.itzhai.com/treemap-sortedmap-interface-implementation-class-introduction-and-implementation-of-custom-comparator-comparator.html
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
SortedMap<Integer, Integer> hash = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
int x = scanner.nextInt();
if (!hash.containsKey(x)) {
hash.put(x, 1);
} else {
int cnt = hash.get(x) + 1;
hash.put(x, cnt);
}
}
scanner.close();
for (Integer key : hash.keySet()) {
System.out.println(key+" "+hash.get(key));
}
}