计算数组中各类型的数有几种,分别是什么

如题,对于一个数组 int [] arr={10,12,12,2,2};,含有10 12 2 三种数,每种数的个数分别为1,2,2

输出的结果为10 出现过1次  12出现过两次 2出现过两次

想法:利用键值对存储,键是数组中不重复的值

          值是那些数字出现的次数

遍历这个数组,对数组的每一个数都判断这个数字之前出现过没有。若没出现过,加入键数组,并且值加1.若出现过,遍历键数组

判断在哪出现过,并且将其值加1

public class Count{
 public static void main(String [] args)
 {
           int [] arr={10,12,12,2,2};
           int count=0; //记录出现的类型总数
           int[] jian=new int [arr.length];
           int[] zhi=new int[arr.length];
         int i=0;int j=0; //记录键值的递增
        for(int a=0;a<arr.length;a++)
       {
              if(b(arr,arr[a],a))   //判断从0-a是否出现过,没出现过加入键值对
             {
                    count++;
                   jian[i++]=arr[a];
                   zhi[j++]++;
             }
              else  //出现过判断是哪一个键值对
            {
                   int temp=nayi(jian,arr[a]);
                  if(temp==-1)
                  {   
                           System.out.println("出错啦"+arr[a]+"%%"+a);
                  }
                 else
                       zhi[temp]++;
           }
     }
      System.out.println("出现过"+count+"种类型,分别是");
     for(int u=0;u<=i-1;u++) //-1因为i有自增操作比长度大一
    {
           System.out.println(jian[u]+"出现过"+zhi[u]+"次");
      }
 }
 public static  boolean b(int arr[],int n,int m){ //判断以前n出现过没有  m下标
            for(int a=0;a<m;a++)
           {
                    if(n==arr[a])
                         return false;
           }
           return true;
 }
 public static int nayi(int jian[],int n)//判断出现过的n在哪个键值对出现
 {
             for(int a=0;a<jian.length;a++)
             {
                  if(n==jian[a])
                       return a;
            }
            return -1;
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值