华为OD机试-阿里巴巴找黄金宝箱

 

 

 

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int[] aa = new int[]{5, 6, 7, 5, 6, 7};
        int k = 10;
        int result = IntStream.range(0, aa.length).mapToObj(idx -> idx + "-" + aa[idx]).collect(Collectors.groupingBy(s -> s.split("-")[1])).entrySet().stream().filter(stringListEntry -> stringListEntry.getValue().size() == 2).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).entrySet().stream().map(stringListEntry -> {
            List<String> value = stringListEntry.getValue();
            int a = Integer.parseInt(value.get(0).split("-")[0]);
            int b = Integer.parseInt(value.get(1).split("-")[0]);
            int abs = Math.abs(a - b);
            if (abs <= k) {
                return abs + "-" + Math.min(a, b);
            }
            return null;
        }).filter(Objects::nonNull).sorted(Comparator.comparingInt(o -> Integer.parseInt(o.split("-")[1]))).collect(Collectors.toList()).stream().limit(1).mapToInt(value -> Integer.parseInt(value.split("-")[1])).findFirst().orElse(-1);
        
        System.out.println(result);
    }
}

 

posted @ 2023-08-13 01:23  手握钢叉的猹  阅读(64)  评论(0编辑  收藏  举报