There is a one-dimensional garden on the x-axis. The garden starts at the point 0
and ends at the point n
. (i.e The length of the garden is n
).
There are n + 1
taps located at points [0, 1, ..., n]
in the garden.
Given an integer n
and an integer array ranges
of length n + 1
where ranges[i]
(0-indexed) means the i-th
tap can water the area [i - ranges[i], i + ranges[i]]
if it was open.
Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.
Example 1:
Input: n = 5, ranges = [3,4,1,1,0,0] Output: 1 Explanation: The tap at point 0 can cover the interval [-3,3] The tap at point 1 can cover the interval [-3,5] The tap at point 2 can cover the interval [1,3] The tap at point 3 can cover the interval [2,4] The tap at point 4 can cover the interval [4,4] The tap at point 5 can cover the interval [5,5] Opening Only the second tap will water the whole garden [0,5]
思路:这题,转换成interval,就是1024,video stitching.
sort by start 解决问题:=> the minimum number of intervals to cover the whole range.
sort by end 解决问题: => the maximum number of non-overlapping intervals.
算法就是:sort by start, 因为前面的也要cover,首先找一个end最大的,然后在start <= end的所有interval中找end最大的。这样就是greedy的思想;如果nextfar >= T, 那么停止,已经找完了,如果nextfar == far说明走不动了,return-1;
class Solution {
public int minTaps(int n, int[] ranges) {
int[][] intervals = new int[n + 1][2];
for(int i = 0; i <= n; i++) {
intervals[i][0] = i - ranges[i];
intervals[i][1] = i + ranges[i];
}
Arrays.sort(intervals, (a, b)->(a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]));
int i = 0;
int far = 0;
int count = 0;
while(i < intervals.length) {
int nextfar = far;
while(i < intervals.length && intervals[i][0] <= far) {
nextfar = Math.max(nextfar, intervals[i][1]);
i++;
}
count++;
if(nextfar >= n) {
return count;
} else if(nextfar == far) {
return -1;
}
far = nextfar;
}
return -1;
}
}