leetcode 452 用最少数量的箭引爆气球

题目: https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/
本例也是直接照抄答案,再加了一点注释。
程序的目录结构如下,
程序目录结构
CMakeLists.txt

cmake_minimum_required(VERSION 2.6)

project(find_min_arrow_shots)
set(CMAKE_CXX_STANDARD 20)
add_definitions(-g)

string(REPLACE ".cpp" "" file "main.cpp")
add_executable(${file}  "main.cpp")

main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>

using namespace std;

class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        if(points.empty()) {
            return 0;
        }

        sort(points.begin(), points.end(), [](vector<int>& u, vector<int>& v){  
            return u[1] < v[1];
        });

        // 最小右值作为初始值
        int pos = points[0][1];
        // 默认第一个球要射一剑
        int ans = 1;
        for(int i=1; i<points.size(); ++i) {
            if(points[i][0] > pos) {
                // 没有交集,需要再射一剑
                ++ans; 
                // 更新pos
                pos = points[i][1];
            }
        }
        // 返回需要射几剑
        return ans;
    }
};

template<typename T>
ostream& operator<<(ostream& os, vector<vector<T>> const& points) {
    stringstream ss;
    for(auto v: points) {
        stringstream inner_ss;
        inner_ss << "[";
        for(auto ele: v) {
            inner_ss << ele << ",";
        }

        // 去掉最右边的逗号
        string inner_str = inner_ss.str();
        inner_str = inner_str.substr(0, inner_str.size()-1);
        ss << inner_str;
        ss << "],";
    }
    // 再次去掉最右边的逗号
    string out_str = ss.str();
    out_str = out_str.substr(0, out_str.size()-1); 
    return os << out_str;
}

auto main(int argc, char** argv) -> int {
    vector<vector<int>> points {{10, 16}, {2, 8}, {1, 6}, {7, 12}};
    Solution s;
    auto arrows = s.findMinArrowShots(points);
    cout << "ballons: " << points << " can be shoot out in: " << arrows << " arrows\n";
    return EXIT_SUCCESS;
}

程序输出如下,
最小数量的箭引爆气球输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值