鱼C论坛

 找回密码
 立即注册
查看: 1123|回复: 1

[技术交流] C++刷leetcode(452. 用最少数量的箭引爆气球)【贪心算法】

[复制链接]
发表于 2020-4-19 17:03:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-4-20 12:40 编辑

题目描述:
  1. 在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。

  2. 一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足  xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

  3. Example:

  4. 输入:
  5. [[10,16], [2,8], [1,6], [7,12]]

  6. 输出:
  7. 2

  8. 解释:
  9. 对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。

  10. 来源:力扣(LeetCode)
  11. 链接:https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons
  12. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>

  4. using namespace std;

  5. int solution(vector<int>& input) {
  6.         if(input.empty()) return 0;
  7.         sort(input.begin(), input.end());
  8.         int len = input.size();
  9.         int count = 0;
  10.         int right = input[0][1];
  11.         for(int i = 1; i < len; i++){
  12.                 if(input[i][0] <= right){
  13.                         count++;
  14.                         right = min(input[i][1], right);
  15.                 }
  16.                 else right = input[i][1];
  17.         }
  18.         return len - count;
  19.    
  20. }

  21. int main(void){
  22.         vector<int> input1
  23.         int number;
  24.         while(cin >> number){
  25.                 input1.push_back(number);
  26.         }
  27.         cout << solution(input1) << endl;
  28.         return 0;
  29. }
复制代码



参考链接:https://leetcode-cn.com/problems ... de-c-by-lu-guo-de-/

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-4-19 17:04:11 | 显示全部楼层
贪心算法好考验智商呀,可惜智商不够
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-6 18:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表