统计数字 (数组去重复)

    开始写之前感觉这题很水,写着写着就发现了一个坑,并且之前竞赛遇见过的一个坑。不详细写过程了,就随便写了个大概的。

    坑就是,统计完了输出,有多少个给我输出了多少了,去不掉重复的元素,思考讨论后决定定义变量,因为已经排好序,输出后给变量赋值,然后下次输出时判断是否与上次的一样,就可以了。

import java.util.*;
public class Test6 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int[] a = new int[n];
		int[] b = new int[n+1];
		
		for(int i=0;i<n;i++) {
			a[i]=input.nextInt();
			b[i]=a[i];
		}
		sort(a,n);
		
		int p=0;
		for(int i=0;i<n;i++) {
			int sum=0;
			for(int j=0;j<n;j++) {
				if(a[i]==a[j])
					sum++;
			}
			
			if(p!=0&&p==a[i])
				continue;
			else
				System.out.println(a[i]+" "+sum);
			p=a[i];
		}
		input.close();
	}
	//排序
	public static void sort(int []a,int n) {
		for(int i=0;i<n;i++) {
			for(int j=i;j<n;j++) {
				int change=0;
				if(a[i]>a[j]) {
					change=a[i];
					a[i]=a[j];
					a[j]=change;
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38786110/article/details/80227949