From 9f38af3e3a61562b17530302e8d14a6a02d1835f Mon Sep 17 00:00:00 2001 From: Hang <69448559+silaslll@users.noreply.github.com> Date: Sun, 5 Jun 2022 17:59:15 -0400 Subject: [PATCH] =?UTF-8?q?Update=200452.=E7=94=A8=E6=9C=80=E5=B0=91?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E7=9A=84=E7=AE=AD=E5=BC=95=E7=88=86=E6=B0=94?= =?UTF-8?q?=E7=90=83.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新了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]) 的原因 加入了时空复杂度和说明 --- .../0452.用最少数量的箭引爆气球.md | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index d4bbe961..58422d4c 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -136,17 +136,28 @@ public: ### Java ```java +/** +时间复杂度 : O(NlogN) 排序需要 O(NlogN) 的复杂度 + +空间复杂度 : O(logN) java所使用的内置函数用的是快速排序需要 logN 的空间 +*/ class Solution { public int findMinArrowShots(int[][] points) { 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; - 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++; + leftmostRightBound = points[i][1]; + //不然就更新最小右边界 } else { - points[i][1] = Math.min(points[i][1],points[i - 1][1]); + leftmostRightBound = Math.min(leftmostRightBound , points[i][1]); } } return count;