算法-区间重叠问题

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-56. 合并区间


下一篇:后缀计算器