Advertisement
imashutosh51

Merge Intervals

Oct 16th, 2022 (edited)
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> merge(vector<vector<int>>& intervals) {
  4.          vector <pair<int,int>> arr;
  5.          for(auto itr:intervals){
  6.             arr.push_back(make_pair(itr[0],itr[1]));  
  7.          }
  8.          sort(arr.begin(),arr.end());
  9.          vector<vector<int>> ans;
  10.          for(int i=0;i<arr.size();){
  11.              vector<int> temp;
  12.              int start=arr[i].first;
  13.              int end=arr[i].second;
  14.              i++;
  15.              while(i<arr.size() && arr[i].first<=end){ end=max(end,arr[i].second);i++;}
  16.              temp.push_back(start);
  17.              temp.push_back(end);
  18.              ans.push_back(temp);
  19.          }  
  20.          return ans;
  21.     }
  22. };
  23.  
  24. /*
  25. Logic:
  26. Sort the array as per the starting value of intervals in increasing order.
  27. Initiliaze a stack and push the first element into it and iterate the array from 1st index.
  28. If starting value of current element is <= the ending value of stack top element then
  29. it should be merged so merge them.
  30. First value of top element will be for sure <= than the first element of current element
  31. because array is sorted. so update the maximum of second values and push it in stack again.
  32. Finally,pop all elements of stack for output.
  33. */
  34.  
  35. class Solution {
  36. public:
  37.     vector<vector<int>> merge(vector<vector<int>>& interval) {
  38.        vector <pair<int,int>> arr;
  39.         for(auto itr:interval){
  40.             arr.push_back(make_pair(itr[0],itr[1]));
  41.         }
  42.         sort(arr.begin(),arr.end());
  43.         stack<pair<int,int>> st;
  44.         st.push(arr[0]);
  45.         for(int i=1;i<arr.size();i++){
  46.             pair<int,int> temp=st.top();
  47.             if(temp.second>=arr[i].first){
  48.                 st.pop();
  49.                 temp.second=max(arr[i].second,temp.second);
  50.                 st.push(temp);
  51.             }
  52.             else{
  53.                 st.push(arr[i]);
  54.             }
  55.         }
  56.         vector <vector <int>> res;
  57.         while(st.size()!=0){
  58.             pair<int,int> itr=st.top();
  59.             st.pop();
  60.             vector <int> temp;
  61.             temp.push_back(itr.first);
  62.             temp.push_back(itr.second);
  63.             res.push_back(temp);
  64.         }
  65.         return res;
  66.     }
  67. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement