leetcode - Merge Intervals
2013-09-12 15:13 张汉生 阅读(151) 评论(0) 编辑 收藏 举报题目描述,点击此处
苍天啊,谁能告诉我为什么11行改成<=就错,难道是快排有问题
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 bool cmp (Interval a,Interval b){ 11 return a.start < b.start; 12 } 13 class Solution { 14 public: 15 int maxInt(const int a, const int b){ 16 return a>b?a:b; 17 } 18 vector<Interval> merge(vector<Interval> &intervals) { 19 // Start typing your C/C++ solution below 20 // DO NOT write int main() function 21 if (intervals.size()<=0) 22 return intervals; 23 sort(intervals.begin(), intervals.end(), cmp); 24 int size = intervals.size(); 25 int validIndex=0; 26 for(int i = 1; i < size ; i++){ 27 if (intervals[i].start <= intervals[validIndex].end) 28 intervals[validIndex].end = maxInt(intervals[validIndex].end, intervals[i].end); 29 else{ 30 intervals[++validIndex] = intervals[i]; 31 } 32 } 33 for (int i=validIndex+1; i<size; i++){ 34 intervals.pop_back(); 35 } 36 return intervals; 37 } 38 };