统计数组元素

package Test;
/**
 * @PackageName: Test
 * @ClassName: Test03
 * @Author:
 * @Date: 2019/8/18 18:25
 * @Description: //统计数组中元素出现的次数
 */
/*第四题:分析以下需求并实现
        (1) 定义方法public static int getCount(int[] arr,int num),求出指定元素在数组中出现的次数.
        (2)定义方法public static int getAllCount(int[] arr),统计数组中出现次数为1的元素一共有多少个。
        (推荐-遍历数组,然后调用第一个方法,求出数组中每个元素在数组中出现的次数,如果只出现了一次,就统计)
        (3) 在main方法中定义数组,如int arr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};。然后调用getAllCount方法,统计只出现一次的元素有多少个。
        打印结果:数组中只出现一次的元素有2个*/

public class Test03 {
    public static void main(String[] args) {
        int[] arr ={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
        int result =getAllCount(arr);
        System.out.println(result);
    }
    public static int getCount(int[] arr,int num){

       /* for (int i = 0; i < arr.length; i++) {
            int count =1;
        }
        for (int j = 0; j <arr.length ; j++) {
            if(arr[j] ==arr[num]){
                count +=1;
            }
        }*/
        int count =0;
        for (int i = 0; i <arr.length ; i++) {
            //如果
            if(arr[i]==num){
                count++;
            }
        }
        return count;
    }
    public static int getAllCount(int[] arr){
        int count =0;
        int[] arr1 =new int[arr.length];
        //求出数组中每个元素在数组中出现的次数,如果只出现了一次,就统计
        for (int i = 0; i < arr.length; i++) {
            //调用第一个方法,求出数组中每个元素在数组中出现的次数,如果只出现了一次,就统计
            arr1[i] = getCount(arr,arr[i]);
            if(arr1[i]==1){
                count ++;
            }
           /* for (int j = i+1; j < arr.length; j++) {
                if(arr[i] ==1){
                   sum ++;
                }
            }*/
        }
        return count;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值