Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 452. Minimum Number of Arrows to Burst Balloons #167

Open
Woodyiiiiiii opened this issue Jan 5, 2023 · 0 comments
Open

Leetcode 452. Minimum Number of Arrows to Burst Balloons #167

Woodyiiiiiii opened this issue Jan 5, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jan 5, 2023

这道题是intervals区间合并的问题。因为我发现类似的区间合并题目都可以用这个做法,所以记录下来。

步骤:

  1. 排序,按从小到大对intervals排序(注意因为直接用Arrays.sort内部的相减的时候,可能会出现爆栈的情况,所以这里我用long做了处理)
  2. 循环遍历,用两个变量来代表上个重叠区间。判断当前区间是否跟下一个区间overlap重叠,是的话则记录重叠区间,到下次循环里判断是否继续重叠,以此作为重叠连续区间的判断;否则继续。
class Solution {
    public int findMinArrowShots(int[][] points) {
        // sort points, first by start, then by end
        // prevent exceeding integer limit
        Arrays.sort(points, (a, b) -> {
            if (a[0] != b[0]) return ((long)(a[0]) - b[0]) > 0 ? 1 : -1;
            return ((long)(a[1]) - b[1]) > 0 ? 1 : -1;
        });

        int l = 0, r = 0;
        int ans = 0;
        for (int i = 0; i < points.length; ++i) {
            if (l == 0 && r == 0) {
                if (i < points.length - 1 && points[i][1] >= points[i + 1][0]) {
                    l = points[i + 1][0];
                    r = Math.min(points[i][1], points[i + 1][1]);
                    ++i;
                }
                ++ans;
            } else {
                if (l >= points[i][0] || r >= points[i][0]) {
                    l = Math.max(l, points[i][0]);
                    r = Math.min(points[i][1], r);
                } else {
                    --i;
                    l = 0;
                    r = 0;
                }
            }
        }

        return ans;
    }
}

intervals类型题目如下,并不难,大部分都是medium难度。


类似的intervals类型题目:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant