452 - Minimum Number Of Arrows To Burst Balloons
#medium
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points
where points[i] = [xstart, xend]
denotes a balloon whose horizontal diameter stretches between xstart
and xend
. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart
and xend
is burst by an arrow shot at x
if xstart <= x <= xend
. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points
, return the minimum number of arrows that must be shot to burst all balloons.
Example 1:
Input: points = [ [10,16],[2,8],[1,6],[7,12] ]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
Example 2:
Input: points = [ [1,2],[3,4],[5,6],[7,8] ]
Output: 4
Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
class Solution {
public:
static bool cmp( vector<int> & a, vector<int> & b ) {
if ( a[0] < b[0] ) return true;
return false;
}
int findMinArrowShots(vector<vector<int>>& points) {
sort( points.begin(), points.end(), cmp );
int result = 1;
int max_value = points[0][1]; // 右邊界
for ( int i = 1; i < points.size(); i++ ) {
if ( points[i][0] > max_value ) {
result++;
max_value = points[i][1];
}
// key point: 第二個區間可能較小,需更新右邊界
else {
max_value = min( points[i][1], max_value );
}
}
return result;
}
};
435 - Non-overlapping Intervals
#medium
Given an array of intervals intervals
where intervals[i] = [starti, endi]
, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: intervals = [ [1,2],[2,3],[3,4],[1,3] ]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
Example 2:
Input: intervals = [ [1,2],[1,2],[1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
Example 3:
Input: intervals = [ [1,2],[2,3] ]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
class Solution {
public:
static bool cmp( vector<int> & a, vector<int> & b ) {
if ( a[0] == b[0] ) return b[1] > a[1];
return b[0] > a[0];
}
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
// 先排序左區間小到大
// 思考 [1,2] [1,3] => 取前面
// 思考 [1,6] [2,4] => 取後面
// 皆取右區間最小的。
int result = 0;
sort(intervals.begin(), intervals.end(), cmp );
int max_value = intervals[0][1];
for ( int i = 1; i < intervals.size(); i++ ) {
if ( intervals[i][0] < max_value ) {
result++;
max_value = min( intervals[i][1], max_value );
}
else {
max_value = intervals[i][1]; // 更新右邊界
}
}
return result;
}