20.10 练习java

1,一道练习题
String string=“aabaaaaaaabccbbccccccccb”;
查询 字符串中每种字符出现的最大间隔
比如第一个a和第二个a之间是0 第二个a和第三个a之间 是1
在这里插入图片描述

我的答案是

 
public class AtomicIntegerTest {


    public static void main(String[] args) {
        String string="aabaaaaaaabccbbccccccccb";
        List<String> relist=new ArrayList<>();
        Set<String> set=new HashSet<>();
        int count=0;
        char[] ch=string.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            set.add(ch[i] + "");
        }
        HashMap<String,Object> map=new HashMap<>();
        set.forEach(x->{
            String in= x;
            char c=in.charAt(0);
            List<Integer> list=new ArrayList<>();
            for (int i = 0; i < ch.length; i++) {
                System.out.print(ch[i]+",");
                System.out.println("传来的值"+c+",");
                if (c==ch[i]) {
                    list.add(i+1);
                }
            }
            map.put(x,list);
            //分组 查询有多少元素
             System.out.println(list);
            int i = maxGap(list.stream().toArray(Integer[]::new));
            System.out.println("最大差"+i);
            int i1 = i - 1;
            relist.add(x+"的最大差是"+i1);
        });
        System.out.println(relist);

    }


    public static int maxGap(Integer ...arr) {
        if (arr == null || arr.length < 2)
            return 0;

        int len = arr.length;

        //表示桶内是否含有元素
        boolean[] hasNum = new boolean[len + 1];
        //表示桶内元素中的最小值
        int[] mins = new int[len + 1];
        //表示桶内元素中的最大值
        int[] maxs = new int[len + 1];

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int bid = 0;

        //找到数组中的最大值和最小值
        for (int e : arr) {
            min = Math.min(min, e);
            max = Math.max(max, e);
        }

        if (min == max)
            return 0;

        for (int i = 0; i < len; i++) {
            bid = bucketId(arr[i], len, min, max);
            mins[bid] = hasNum[bid] ? Math.min(mins[bid], arr[i]) : arr[i];
            maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], arr[i]) : arr[i];
            hasNum[bid] = true;
        }

        int res = 0;
        int preMax = maxs[0];
        for (int i = 1; i <= len; i++) {
            if (hasNum[i]) {
                res = Math.max(res, mins[i] - preMax);
                preMax = maxs[i];
            }
        }
        return res;
    }

    //判断整数item所属桶的id
    public static int bucketId(int num, int len, int min, int max) {
        return ((num - min) * len / (max - min));
    }

  

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值