Update 0452.用最少数量的箭引爆气球.md

更新了java代码,增加了一个 leftmostRightBound variable 记录最小的右边界使得代码可读性增加
加入了comment
解释了Arrays.sort(points, (x, y) -> Integer.compare(x[0], y[0])); 中不用 x[0] - y[0] 而是用Integer.compare(x[0], y[0]) 的原因
加入了时空复杂度和说明
This commit is contained in:
Hang
2022-06-05 17:59:15 -04:00
committed by GitHub
parent be18cd3961
commit 9f38af3e3a

View File

@ -136,17 +136,28 @@ public:
### Java ### Java
```java ```java
/**
时间复杂度 : O(NlogN) 排序需要 O(NlogN) 的复杂度
空间复杂度 : O(logN) java所使用的内置函数用的是快速排序需要 logN 的空间
*/
class Solution { class Solution {
public int findMinArrowShots(int[][] points) { public int findMinArrowShots(int[][] points) {
if (points.length == 0) return 0; if (points.length == 0) return 0;
Arrays.sort(points, (o1, o2) -> Integer.compare(o1[0], o2[0])); //用x[0] - y[0] 会大于2147483647 造成整型溢出
Arrays.sort(points, (x, y) -> Integer.compare(x[0], y[0]));
//count = 1 因为最少需要一个箭来射击第一个气球
int count = 1; int count = 1;
for (int i = 1; i < points.length; i++) { //重叠气球的最小右边界
if (points[i][0] > points[i - 1][1]) { int leftmostRightBound = points[0][1];
//如果下一个气球的左边界大于最小右边界
if (points[i][0] > leftmostRightBound ) {
//增加一次射击
count++; count++;
leftmostRightBound = points[i][1];
//不然就更新最小右边界
} else { } else {
points[i][1] = Math.min(points[i][1],points[i - 1][1]); leftmostRightBound = Math.min(leftmostRightBound , points[i][1]);
} }
} }
return count; return count;