List集合中根据指定个数进行分组,找出分组的和与目标值最接近的组合

List集合中根据指定个数进行分组,找出分组的和与目标值最接近的组合

废话不多说,直接开干。

import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @ClassName: Test
 * @Description: 求集合中指定个数分组的和最接近目标值的的组
 **/
public class Test {
    //待计算的数据
    private static List<Integer> list = Arrays.asList(232, 2324, 5423, 1552, 354, 1545, 380, 154, 1542, 4158, 2152);
    //目标值
    private static Integer sum = 5800;

    //定义需要进行计算值的个数
    private static int num = 2;

    private static Map<Long, String> map = new HashMap<>();
    private static List<Long> sumList = new ArrayList<>();
    private static List<Integer> tmpArr = new ArrayList<>();


    public static void main(String[] args) {
        if (num > list.size() || list.size() <= 0) {
            return;
        }
        combine(0, num);
        Long index = getValue();
        System.out.println("获取到" + num + "个数的和最接近目标值:" + sum + "的数分别为:" + map.get(index) + "--和为:" + index);
    }

    public static void combine(int index, int k) {
        if (k == 1) {
            for (int i = index; i < list.size(); i++) {
                tmpArr.add(list.get(i));
//                System.out.println(tmpArr.toString());
                IntSummaryStatistics summaryStatistics = tmpArr.stream().mapToInt((s) -> s).summaryStatistics();
                long sum = summaryStatistics.getSum();
                String value = map.get(sum);
                if (StringUtils.isNotEmpty(value)) {
                    if (!tmpArr.toString().equals(value)) {
                        map.put(sum, tmpArr.toString() + "或者" + value);
                    }
                } else {
                    map.put(sum, tmpArr.toString());
                    sumList.add(sum);
                }
                tmpArr.remove(list.get(i));
            }
        } else if (k > 1) {
            for (int i = index; i <= list.size() - k; i++) {
                tmpArr.add(list.get(i));
                combine(i + 1, k - 1);
                tmpArr.remove(list.get(i));
            }
        } else {
            return;
        }
    }

    /**
     * @description: 找出最接近目标值值的key
     **/
    private static Long getValue() {
        Long index;
        //获取接近值
        if (sumList == null) {
            return null;
        }
        if (sumList.size() == 1) {
            index = sumList.get(0);
        }
        Long minDifference = Math.abs(sumList.get(0) - sum);
        int minIndex = 0;
        for (int i = 1; i < sumList.size(); i++) {
            Long temp = Math.abs(sumList.get(i) - sum);
            if (temp < minDifference) {
                minIndex = i;
                minDifference = temp;
            }
        }
        index = sumList.get(minIndex);
        return index;
    }
}

最终结果为:

获取到2个数的和最接近目标值:5800的数分别为:[5423, 380]--和为:5803

若还有更好的欢迎留下你宝贵的idea.

上一篇:三数之和


下一篇:「美团 CodeM 初赛 Round B」送外卖2