蓝桥 算法训练 数的统计 JAVA

两种解法:第一种较为简单,第二种要看知识点哦~

问题描述
  在一个有限的正整数序列中,有些数会多次重复出现在这个序列中。
  如序列: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));
		}
	}

小剧场:性格开朗,充满希望。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值