[编程题]合并区间 |
您所在的位置:网站首页 › java输入一行整数空格隔开 › [编程题]合并区间 |
牛客网:https://www.nowcoder.com/questionTerminal/0596b6232ce74b18b60ba0367d7f2492 [编程题]合并区间用x,y表示一个整数范围区间,现在输入一组这样的范围区间(用空格隔开),请输出这些区间的合并。 输入描述:一行整数,多个区间用空格隔开。区间的逗号是英文字符。 输出描述:合并后的区间,用过空格隔开,行末无空格 示例1输入 1,3 2,5输出 1,5 示例2输入 1,3 2,5 8,10 11,15输出 1,5 8,10 11,15 思路 贪心,对x排序,剩下的就很简单了 #include #include #include #include #include #include #include using namespace std; int main() { string ch; char a; int x, y; vector xy,ans; while (getline(cin, ch))//看题意还以为要处理下,其实直接读就行,做麻烦了 { xy.clear(); ans.clear(); stringstream strcin(ch); while (strcin >> x >> a >> y) { if (x > y)swap(x, y); xy.emplace_back(x,y); } stable_sort(xy.begin(), xy.end()); ans.push_back(*xy.begin()); auto an = ans.begin(); for (auto it = xy.begin()+1; it != xy.end(); it++) { if (an->second >= it->first ) { an->second = max(an->second, it->second); } else if(an==ans.end()-1) { ans.push_back(*it); an = ans.end()-1; } } for (auto &key : ans) { cout |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |