排列后的数组进行归并,得最小人数构造完美答案

package StringSS;

/**
 * 按第一维度升序,第二维度降序排列之后的数组,进行归并
 * 1 6
 * 1 3
 * 4 7
 * 8 10
 */

public class MinPeople {
    public static void comp(int peoples, int questions, int[][] correctRanges) {
        // 剪枝
        if (correctRanges[0][0] != 1) {
            System.out.println(-1);
            return;
        }
        if (correctRanges[0][1] == questions) {
            System.out.println(1);
            return;
        }
        int max = correctRanges[0][1];
        int right = correctRanges[0][1];
        int res = 1;
        for (int i = 0; i < correctRanges.length;) {
            for (int j = i+1; j < correctRanges.length; j++) {
                // 此循环用于寻找下一个最大的合并区间 max记录,更新max
                if (correctRanges[j][0] == right+1 || right >= correctRanges[j][0] && right < correctRanges[j][1]) {
                    // 这种情况的j行就符合,
                    if (correctRanges[j][1] >= max) {
                        max = correctRanges[j][1];
                        i = j;
                    }
                }
                // 对于不连续情况,剪枝,肯定就不符合了,直接返回-1
                if (correctRanges[j][1] > right+1) {
                    break;
                }
            }
            if (max > right) {
                res++;
                right = max;
            } else {
                System.out.println(-1);
                return;
            }
            // 提前结束剪枝
            if (right == questions) {
                System.out.println(res);
                return;
            }
        }
        System.out.println(res);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值