leetcode 452. Minimum Number of Arrows to Burst Balloons

題目452. Minimum Number of Arrows to Burst Balloons
等級: medium
標籤:貪心

思路

對pair,以第一個元素爲第一排序準則,第二個元素爲次要準則排序。
然後從小到大掃描,尋找連續的有交疊部分的pair,然後銷燬,計數加一,繼續此操作至尾部,計數結果即爲答案

實現

# include <iostream>
# include <Vector>
# include <algorithm>

using namespace std;

bool cmp(pair<int, int> a, pair<int, int> b) {
    return a.first < b.first || (a.first == b.first && a.second < b.second);
}

class Solution {
public:
    int findMinArrowShots(vector<pair<int, int> >& points) {
        int size = points.size();
        if(size <= 1) return size;

        sort(points.begin(), points.end(), cmp);
        int index = 0, border = 0, ret = 0;
        border = points[index].second;

        while(1) {
            ret++;
            while(index < size && points[index].first <= border) {
                if(points[index].second < border)
                    border = points[index].second;
                index++;    
            };
            if(index >= size) break;

            // update the border
            border = points[index].second;  
        }   
        return ret;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章