力扣经典面试题——合并区间

2023-12-13 05:35:04
合并区间

https://leetcode.cn/problems/merge-intervals/description/?envType=study-plan-v2&envId=top-interview-150

![外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传](https://img-home.csdnimg.cn/images/2片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传](https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=C%3A%5CUsers%5CXT189%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20231211235119360.png&pos_id=img-NPA5kDIJ-170230724024159.ng?origin_url=C%3A%5CUsers%5CXT189%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20231211235119360.png&pos_id=img-SiDH5Jka-1702309942246

这题思维量一般但比较考察API的使用。

1、数组的自定义排序
2、数组的初始化定义
3、Arrays转int

通过重写Comparator的compare方法来自定义排序规则,返回的值看正负。

 Arrays.sort(intervals,new Comparator<int[]>(){
    public int compare(int[] a,int[] b){
        return a[0]-b[0];
    }
});
class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,new Comparator<int[]>(){
            public int compare(int[] a,int[] b){
                return a[0]-b[0];
            }
        });
        List<int[]> merge = new ArrayList<>();
        merge.add(intervals[0]);
        for(int i=1;i<intervals.length;i++){
            int left = intervals[i][0];
            int right = intervals[i][1];
            int merge_left = merge.get(merge.size()-1)[0];
            int merge_right = merge.get(merge.size()-1)[1];
            if(left>=merge_left&&left<=merge_right){
                int[] temp = {merge_left,Math.max(right,merge_right)};
                merge.set(merge.size()-1,temp);
            }else{
                merge.add(intervals[i]);
            }
        } 
        //再转化成数组
        return merge.toArray(new int[merge.size()][]);
    }
}

文章来源:https://blog.csdn.net/qq_45816864/article/details/134939027
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。