greedy——452. Minimum Number of Arrows to Burst Balloons[medium]

題目描述

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons. 

Example:

Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

抽象出來的意思是,選取一個數,讓它經過最多的區間數,問這樣的數至少有幾個。


解題思路


貪心算法,局部最優解 = 整體最優解,每次選一個經過最大區間的數(其實不用確定這個數,只要計算重疊區間數,所有重疊區間都可以用一個數穿過),一直到經過所有區間爲止。解題示意圖如下:




從圖中得到算法如下:

1、給pair排序,默認排序就是按第一個大小,第一個相同再比較第二個,升序排好

2、遍歷數組,用tmp(第i個數組元素)表示當前區間,檢查當前區間與檢查到的區間是否有重疊,重疊的話,tmp = 重疊部分,一直進行下去

3、如果無重疊,則tmp = 檢查到的區間,表示arrow的計數器++,重複2


代碼如下


class Solution {
public:
  bool inter(pair<int, int> a, pair<int, int> b) {
	if (a.second < b.first || b.second < a.first)
		return false;

	return true;
}

int findMinArrowShots(vector<pair<int, int>>& points) {
	if (points.empty())
		return 0;
	sort(points.begin(), points.end());

	int count = 0;

	for (int i = 0; i < points.size(); i++) {
		pair<int, int> tmp = points[i];
		int j = i + 1;

		for (j; j < points.size(); j++) {
			if (inter(tmp, points[j])) {
				tmp.first = fmax(tmp.first, points[j].first);
				tmp.second = fmin(tmp.second, points[j].second);
				continue;
			}
				break;
		}

		i = j - 1;
		count++;
	}

	return count;
}
};


inter函數判斷是否有交集。

fmax返回兩者較大者,fmin相反。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章