[Leetcode] 56. Merge Intervals

whitehousechef·2025년 8월 15일

https://leetcode.com/problems/merge-intervals/description/

initial

typical interval q but with java be careful

sol

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(a,b)-> Integer.compare(a[0],b[0]));
        int[] tmp = intervals[0];
        List<int[]> ans = new ArrayList<>();
        ans.add(tmp);
        for(int i = 1; i< intervals.length;i++){
            if(intervals[i][0]<=tmp[1]){
                tmp[1]=Math.max(intervals[i][1],tmp[1]);
            } else{
                tmp=intervals[i];
                ans.add(tmp);
            }
        }
        return ans.toArray(new int[ans.size()][]);
    }
}

complexity

n log n cuz of sort?
max n space?

0개의 댓글