Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mergeIntervals.cpp #64

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions Arrays/mergeIntervals.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include <bits/stdc++.h>
using namespace std;
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool comp(Interval i1,Interval i2){
if(i1.start<i2.start){
return true;
}
return false;
}
vector<Interval> Solution::insert(vector<Interval> &intervals, Interval newInterval) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int i,n,e,s;
intervals.push_back(newInterval);
sort(intervals.begin(),intervals.end(),comp);
stack<Interval>st;
st.push(intervals[0]);
n=intervals.size();
for(i=1;i<n;i++){
Interval t=st.top();
if(t.end>=intervals[i].start){
st.pop();
Interval in;
in.start=t.start;
in.end=max(t.end,intervals[i].end);
st.push(in);
}
else{
st.push(intervals[i]);
}
}
intervals.clear();
while(!st.empty()){
Interval in=st.top();
intervals.push_back(in);
st.pop();
}
sort(intervals.begin(),intervals.end(),comp);
return intervals;
}