一道简单的算法题

题目:字符序列,[1,3,2,1,7,5,4,9]找出现次数最多的最大的字符


其实题意不是很明确,比如这个字符包不包含英文字母。

这里强调是数字字符:

思路:排序,1,1,2,3,4,5,9

参考实现,代码不是很好看:

//题目:字符序列,[1,3,2,1,7,5,4,9]找出现次数最多的最大的字符
public class No1 {
    public static void main(String[] args) {
        int array[] = {3, 3, 2, 1, 7, 5, 4, 5};
        if (1 == array.length) {
            System.out.println("结果出现次数最多的是1次,最大的字符是" + array[0]);
            exit(1);
        }
        //先排序
        sort(array);
        int preMaxCount = 1;
        int preMaxInt = array[0];
        int curInt = 0;
        int curMaxCount = 0;
        int i = 1;
        //记录一个之前最大字符,和之前最大次数,以及当前位置的次数
        //先找到第一个字符的结束,到与其不同的第二个字符开始
        for (; i < array.length; i++) {
            if (preMaxInt == array[i]) {
                preMaxCount++;
            } else {
                curMaxCount++;
                curInt = array[i];
                i++;
                break;
            }
        }
        //从第二个字符开始接着循环替换之前最大字符和次数
        for (; i < array.length; i++) {

            if (curInt == array[i]) {
                curMaxCount++;
            } else {
                if (preMaxCount <= curMaxCount) {
                    preMaxCount = curMaxCount;
                    preMaxInt = curInt;
                }
                curMaxCount = 1;
                curInt = array[i];
            }
        }
        if (preMaxCount <= curMaxCount) {
            preMaxCount = curMaxCount;
            preMaxInt = curInt;
        }
        System.out.println("结果出现次数最多的是" + preMaxCount + "次,最大的字符是" + preMaxInt);
    }

    public static void sort(int array[]) {
        //冒泡,把最大的放右边
        int temp = 0;
        for (int i = array.length - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值