LeetCode Brush Question: Greedy Algorithm [452. Detonate the balloon with the least number of arrows] - Java version

Greedy Algorithm: Assignment Questions
Just record your own process of brushing questions, and the answers refer to a variety of question solutions.

Thank you for correcting me if I make any mistakes!

Reference: LeetCode 101: A LeetCode Grinding Guide (C++ Version) Author: Gao Chang Chang Gao

Source of questions: Question Bank - LeetCode, the global geek's favorite technology growth platform (leetcode-cn.com)

452. Explode a balloon with the fewest number of arrows (Medium)

  • Local greed is reflected in the fact that each shot of an arrow detonates as many balloons as possible.

  • Global greed is reflected in detonating all the balloons with the fewest arrows.

  • The smaller the selected balloon starts , the more balloons will be included, reducing the number of arrows. Sort in ascending order of the left boundary value and traverse from left to right, because it is necessary to shoot arrows where the balloons overlap the most densely as possible.

  • Each time the interval with the smallest start and no intersection with the previous selected interval is selected, the number of non-overlapping balloons == the number of arrows . If the left boundary value of the current balloon A is greater than the right boundary value of the previous balloon B, add one to the unique number, that is, add one to the number of arrows; and update the end value to the right boundary value of the current group, and then start from the current balloon Start a new round of judgment.

public int findMinArrowShots(int[][] points) {
    if (points.length == 0) {
        return 0;
    }
    // 按照右边界值排序
    Arrays.sort(points, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            if (o1 != o2) {
                return Integer.compare(o1[1], o2[1]);
            } else {
                return Integer.compare(o1[0], o2[0]);
            }
        }
    });
    int count = 1; //非重叠个数初始化为1
    int end = points[0][1]; //边界值初始化为第一位的右值
    for (int i = 1; i < points.length; i++) {
        if (end < points[i][0]) { //当前气球A的左边界值,大于前一个气球B的右边界值,则非重复数加一
            count++; //非重叠气球的个数就是射箭数
            end = points[i][1]; //从当前这个气球开始新一轮的判断
        }
    }
    return count;
}

おすすめ

転載: blog.csdn.net/weixin_51909882/article/details/122152225