题目

https://leetcode.com/problems/interval-list-intersections/
在这里插入图片描述

题解

本题用双指针。(想了下,也可以用线段树,和天际线那道题类似)

class Solution {
    public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
        int i = 0;
        int j = 0;
        List<int[]> list = new ArrayList<>();
        while (i < firstList.length || j < secondList.length) {
            if (i == firstList.length) {
                j++;
            } else if (j == secondList.length) {
                i++;
            } else {
                // 有重叠情况:
                // [    ]
                //    [    ]

                //  [   ]
                // [       ]

                //    [    ]
                // [    ]

                // [       ]
                //  [   ]

                // 无重叠情况:
                // [    ]
                //        [    ]

                //        [    ]
                // [    ]
                int start = Math.max(firstList[i][0], secondList[j][0]);
                int end = Math.min(firstList[i][1], secondList[j][1]);
                if (start <= end) {
                    list.add(new int[]{start, end});
                    if (firstList[i][1] < secondList[j][1]) {
                        i++;
                    } else {
                        j++;
                    }
                } else {
                    if (firstList[i][1] < secondList[j][0]) {
                        i++;
                    } else {
                        j++;
                    }
                }
            }
        }
        int[][] result = new int[list.size()][];
        for (int k = 0; k < list.size(); k++) {
            result[k] = list.get(k);
        }
        return result;
    }
}

在这里插入图片描述

Logo

「智能机器人开发者大赛」官方平台,致力于为开发者和参赛选手提供赛事技术指导、行业标准解读及团队实战案例解析;聚焦智能机器人开发全栈技术闭环,助力开发者攻克技术瓶颈,促进软硬件集成、场景应用及商业化落地的深度研讨。 加入智能机器人开发者社区iRobot Developer,与全球极客并肩突破技术边界,定义机器人开发的未来范式!

更多推荐