在1000个数中找出出现次数最多的数

输出出现最多的数

package com.fonxian.findmax;
/*
问题: 
在一个由自然数1-1000中某些数字所组成的数组中,每个数字可能出现零次或者多次。
设计一个算法,找出出现次数最多的数字。
*/
public class FindMax {
    static int findMax(int[] a,int n){

        int num;//a中的元素,temp的下标
        int max = 0;
        int[] temp = new int[1000];

        //将数组中的元素设为0,意为出现0次
        for(int i = 0;i<1000;i++)
            temp[i] = 0;

        //a数组中的元素转换为temp数组的下标,temp中的元素则为出现的次数
        for(int j = 0;j < n;j++){
            num = a[j];
            temp[num]++;
        }

        //找到出现次数最多的数
        for(int t = 0;t<1000;t++){
            if(temp[t]>max)
                max = t;
        }

        return max;
    }
    public static void main(String[] args) {
        int[] a={1,2,3,4,5,4,5,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8};
        System.out.println("出现次数最多的数为:"+findMax(a,a.length));
    }
}

测试结果

“出现次数最多的数为:8

输出出现次数最多的前三个数

使用选择排序的思想,来找出现次数最多的前三个数

//输出出现次数最多的三个数
        int key;//用来保存下标
        int j;
        int flag=0;//标记用来判断是否满足3个数
        int[] number = new int[3];
        for(int i = 0;i<1000&&flag!=3;i++){
            key = i;
            for(j=i;j<1000;j++){
                if(temp[j]>temp[key])
                    key = j;
            }
            exch(temp,i,key);
            number[flag]=key;
            flag++;     
        }
        for(int i = 0;i<3;i++)
            System.out.println(number[i]);

exch函数

    //交换两个数组的值
    static void exch(int[] a,int i,int j){
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;    
    }

测试结果
8
7
5

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值