xinyu04

导航

LeetCode 986 Interval List Intersections 模拟

You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

A closed interval [a, b] (with \(a \le b\)) denotes the set of real numbers x with \(a\le x \le b\).

The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

Solution

直接分情况讨论即可

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
    
public:
    vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
        int n1 = firstList.size(), n2 = secondList.size();
        if(n1==0||n2==0)return ans;
        
        int l1=0, l2=0;
        while(l1<n1 && l2<n2){
            if(firstList[l1][0]<=secondList[l2][0]){
                
                if(firstList[l1][1]>=secondList[l2][0]){
                // [    ] ---> first
                //   [    ] ---> second
                    if(firstList[l1][1]<=secondList[l2][1]){
                        
                       ans.push_back({secondList[l2][0],firstList[l1][1]}); l1+=1;                 
                    }
                    else{
                        // [   ] ->first
                        //   [] ->second
                        ans.push_back({secondList[l2][0], secondList[l2][1]});l2+=1;
                    }

                }
                else{
                    // [    ] ->first
                    //       [    ] ->second
                    l1+=1;
                }
                
            }
            else{
                
                if(firstList[l1][0]<=secondList[l2][1]){
                    
                    if(firstList[l1][1]>=secondList[l2][1]){
                        // [    ] ->first
                        //[    ] ->second
                        ans.push_back({firstList[l1][0],secondList[l2][1]});l2++;
                    }
                    else{
                        //   [   ] ->first
                        //  [     ] ->second
                        ans.push_back({firstList[l1][0], firstList[l1][1]}); l1++;
                    }
                    
                }
                else{
                    //    [   ] ->first
                    //[  ] ->second
                    l2++;
                }
            }
        }
        return ans;
    }
};

posted on 2022-07-31 16:59  Blackzxy  阅读(16)  评论(0编辑  收藏  举报