theshy

博客园 首页 新随笔 联系 订阅 管理

leetcode 56.合并区间

import java.util.Arrays;
import java.util.Comparator;

class Solution {
    public int[][] merge(int[][] intervals) {
        //sort
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        int n = intervals.length;
        int prex = intervals[0][0], prey = intervals[0][1];
        int[][] ans = new int[n][2];
        int idx = 0;
        for (int i = 1; i < n; i++) {
            if (intervals[i][0] <= prey) {
                prey = Math.max(prey,intervals[i][1]);
            } else {
                ans[idx][0] = prex;
                ans[idx++][1] = prey;
                prex = intervals[i][0];
                prey = intervals[i][1];
            }
        }
        ans[idx][0] = prex;
        ans[idx++][1] = prey;
        int[][] ans2 = new int[idx][2];
        for (int i = 0; i < idx; i++) {
            ans2[i][0] = ans[i][0];
            ans2[i][1] = ans[i][1];
        }
        return ans2;
    }
}

 

leetcode 435. 无重叠区间

 类比射气球

import java.util.Arrays;
import java.util.Comparator;

class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });
        int prex = intervals[0][0], prey = intervals[0][1];
        int n = intervals.length;
        int x = 0;
        for (int i = 1; i < n; i++) {
            if (intervals[i][0] < prey) {
                x++;
            } else {
                prey = intervals[i][1];
            }
        }
        return x;
    }
}

 

 

leetcode 452. 用最少数量的箭引爆气球

import java.util.Arrays;
import java.util.Comparator;

class Solution {
    public int findMinArrowShots(int[][] points) {
        Arrays.sort(points, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[1] < o2[1]) {
                    return -1;
                } else if (o1[1] > o2[1]) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        int prex = points[0][0], prey = points[0][1];
        int n = points.length;
        int ans = 0;
        for (int i = 1; i < n; i++) {
            if (points[i][0] > prey) {
                ans++;
                prey = points[i][1];
            }
        }
        ans++;
        return ans;
    }
}

 

posted on 2022-01-01 19:50  tziSher  阅读(130)  评论(0编辑  收藏  举报