986 - Interval List Intersections

解法一 - Merge interval

這題非常具代表性,我們可以把各種情況列舉出來,再合併相同的 case:

只要寫出上面的 case,要轉換 code 就變得很容易了:

class Solution {
public:
    vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
        vector<vector<int>> res;
        int i = 0, j = 0;

        while(i < A.size() and j < B.size()) {
            if(A[i][1] < B[j][0]) {
                ++i;
            }
            else if(B[j][1] < A[i][0]) {
                ++j;
            }
            else {
                res.push_back({
                    max(A[i][0], B[j][0]), 
                    min(A[i][1], B[j][1])
                });

                if(A[i][1] < B[j][1]) { ++i; }
                else { ++j; }
            }
        }

        return res;
    }
};

results matching ""

    No results matching ""