算法训练:Minimum Number of Arrows to Burst Balloons
来源:互联网 发布:瘦咬肌的成功经验知乎 编辑:程序博客网 时间:2024/04/30 22:58
题目链接:https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/#/description
题目描述:
用区间范围来表示气球的大小,可能会有重叠区间。[start,end]只要箭在这个区间内,那么就可以射中气球,如果两个区间有重叠,那么在重叠区
间射箭,可以一箭双雕。求将所有的气球射破的最少的箭数。
解题思路:
首先对给定的所有区间进行排序,按照第一个数递增排序,如果第一个数相等,则按照第二个数递增排序。首先初始化射箭次数res=1(至少需要一
箭),end为第一个区间的结束坐标,然后从第二个区间开始遍历。如果下一个气球的开始坐标小于当前结束坐标,说明可以射击一次完成,否则需要
增加射击次数,并且重置当前结束坐标两个结束坐标中较小的那个。例如,[2,8]和[1,6]的重复区域是[2,6],在此区间射箭,只需一箭就可以将两个气球
射破,[7,12]和[2,8]重复区域为[7,8],在[2,6]区间射箭的话达不到该区域,所以需要射击两次。
public int findMinArrowShots(int[][] points) { // Arrays.sort(points, new MyComprator()); //使用指定的排序器,进行排序 if (points.length == 0 || points[0].length == 0) { return 0; } Arrays.sort(points, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0]==b[0]) return a[1]-b[1];//第一个数相同,按第二个数升序排列 return a[0] - b[0];//按第一个数升序排列 } }); int res = 1, end = points[0][1]; for (int i = 1; i < points.length; ++i) { if (points[i][0] <= end) {//两个区间有重合 end =end<points[i][1]?end:points[i][1]; } else { ++res;//无重合需要再射一箭 end = points[i][1]; } } return res; }
运行结果:
Your Input
[[10,16],[2,8],[1,6],[7,12],[9,15]]
Your answer
2
Expected answer
2
0 0
- 算法训练:Minimum Number of Arrows to Burst Balloons
- Minimum Number of Arrows to Burst Balloons
- Minimum Number of Arrows to Burst Balloons
- Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- 452. Minimum Number of Arrows to Burst Balloons
- 【leetcode】452. Minimum Number of Arrows to Burst Balloons【M】
- 452. Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- 452. Minimum Number of Arrows to Burst Balloons
- 452. Minimum Number of Arrows to Burst Balloons
- Leetcode 452. Minimum Number of Arrows to Burst Balloons[medium]
- [leetcode 452]Minimum Number of Arrows to Burst Balloons
- 452. Minimum Number of Arrows to Burst Balloons
- [leetcode] 452. Minimum Number of Arrows to Burst Balloons
- Leetcode-452. Minimum Number of Arrows to Burst Balloons
- 【LeetCode】 452. Minimum Number of Arrows to Burst Balloons
- 452. Minimum Number of Arrows to Burst Balloons
- java中的File类常用方法
- 【cocos2d-x教程】如何使用WebSocket
- java 中逻辑运算符&与&&,|与||
- bacula源码安装配置
- JavaEE开发之Tomcat安装详解
- 算法训练:Minimum Number of Arrows to Burst Balloons
- 如何查看APP Activity / APP Package
- android 录制视频清晰度问题
- 目标跟踪测试数据汇总
- JSON简单应用
- win7卸载oracle
- phpcms更改模块信息问题
- 如何使用OSS更省钱!
- 深入理解SELinux/SEAndroid 第二部分