LeetCode 57. Insert Interval

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
static auto x = []()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();
class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        vector<vector<int>> ret;
        for(vector<int>& v : intervals){
            if(v[0]>newInterval[1]){
                ret.push_back(v);
            }
            else if(v[1]<newInterval[0]){
                ret.push_back(v);
            }
            else{
                if(newInterval[0]>v[0]){
                    newInterval[0]=v[0];
                }
                if(newInterval[1]<v[1]){
                    newInterval[1]=v[1];
                }
            }
        }
       
        bool inserted=false;
        vector<vector<int>>::iterator it=ret.begin();
        while(it!=ret.end()){
            if((*it)[0]<newInterval[0]){
                ++it;
            }
            else{
                ret.insert(it,newInterval);
                inserted=true;
                break;
            }
        }
        if(!inserted){
             ret.push_back(newInterval);
        }
        return ret;
    }
};



5 Replies to “LeetCode 57. Insert Interval”

  1. I was wondering if you ever thought of changing
    the structure of your site? Its very well written; I
    love what youve got to say. But maybe you could
    a little more in the way of content so people could connect with it better.

    Youve got an awful lot of text for only having one or
    two images. Maybe you could space it out better?

  2. Howdy, i read your blog occasionally and i own a similar one and i was just wondering
    if you get a lot of spam remarks? If so how do you
    protect against it, any plugin or anything you can advise?
    I get so much lately it’s driving me mad so any assistance is
    very much appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *