1. 程式人生 > 其它 >leetcode-華為專題-56. 合併區間

leetcode-華為專題-56. 合併區間

class Solution {
public:
    static bool cmp(vector<int> &a, vector<int> &b){
        // if(a[0]!=b[0])
            return a[0]<b[0];
        // else 
        //     return a[1]<b[1];
    }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector
<vector<int>> res; sort(intervals.begin(), intervals.end(),cmp); vector<int> temp; temp.push_back(intervals[0][0]); temp.push_back(intervals[0][1]); for(int j = 1; j < intervals.size(); j++){ if(intervals[j][0]<=temp[1
]){ // 可以加入區間 if(intervals[j][1]>temp[1]) // 如果當前元素右邊界大於當前區間的右邊界 temp[1] = intervals[j][1]; // 更新右邊界 }else{ res.push_back(temp); temp[0] = intervals[j][0]; temp[1] = intervals[j][1]; } } res.push_back(temp);
return res; } };