算法
这个题目感觉很像是Leetcode里面的jump game II, 可以贪心选择区间。
链接如下:
https://leetcode.com/problems/jump-game-ii/
https://leetcode-cn.com/problems/jump-game-ii/
Java 代码
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), T = in.nextInt();
int[][] intervals = new int[n][2];
for (int i = 0; i < n; ++i) {
intervals[i][0] = in.nextInt();
intervals[i][1] = in.nextInt();
}
in.close();
System.out.println(minCows(n, T, intervals));
}
private static int minCows(int n, int T, int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
int count = 1;
int curRight = 0, curLeft = 1;
for (int i = 0; i < n; ++i) {
if (intervals[i][0] <= curLeft) {
curRight = Math.max(curRight, intervals[i][1]);
} else if (intervals[i][0] > curRight + 1) {
return -1;
} else {
if (curRight == T) return count;
curLeft = curRight + 1;
curRight = Math.max(curRight, intervals[i][1]);
count++;
}
}
return curRight == T ? count : -1;
}
}