Advertisement
vaibhav1906

Merge Intervals

Nov 19th, 2021
1,715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> merge(vector<vector<int>>& intervals) {
  4.        
  5.         sort(intervals.begin(), intervals.end(), [](vector<int> a, vector<int>b){
  6.            
  7.             if(a[0]<b[0]){
  8.                 return true;
  9.             }
  10.            
  11.             return false;
  12.            
  13.         });
  14.        
  15.        
  16.         vector<vector<int>> ans;
  17.        
  18.         for(int i = 0; i<intervals.size(); i++){
  19.            
  20.             if(ans.size()==0){
  21.                 ans.push_back(intervals[i]);
  22.             }
  23.            
  24.             else if(ans[ans.size()-1][1] <intervals[i][0]){
  25.                 ans.push_back(intervals[i]);
  26.             }
  27.            
  28.             else{
  29.                 ans[ans.size()-1][1] = max(ans[ans.size()-1][1], intervals[i][1]);
  30.             }
  31.         }
  32.        
  33.         return ans;
  34.        
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement