LeetCode: Merge Intervals

出了个小问题,但是这问题又那么蛋疼。。bool cmp这函数不能放在solution里,我也不知道为什么,放外面就能过

 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(const Interval a, const Interval b) {

11     if (a.start == b.start) return a.end < b.end;

12     return a.start < b.start;

13 }

14 class Solution {

15 public:

16     vector<Interval> merge(vector<Interval> &intervals) {

17         // Start typing your C/C++ solution below

18         // DO NOT write int main() function

19         sort(intervals.begin(), intervals.end(), cmp);

20         vector<Interval> ret;

21         for (int i = 0; i < intervals.size(); i++) {

22             if (!ret.size() || intervals[i].start > ret.back().end) ret.push_back(intervals[i]);

23             else ret.back().end = max(ret.back().end, intervals[i].end);

24         }

25         return ret;

26     }

27 };

 C#:注意两个问题,1,IList并没有sort函数,因此要先转换成List,2,intervals的sort函数的排序有两种方法,注释里的也可以用,随便选,这里sort里的必须是Comparison<Interval>或者IComparer<Interval>的,都必须是静态(static)的

 1 /**

 2  * Definition for an interval.

 3  * public class Interval {

 4  *     public int start;

 5  *     public int end;

 6  *     public Interval() { start = 0; end = 0; }

 7  *     public Interval(int s, int e) { start = s; end = e; }

 8  * }

 9  */

10 public class Solution {

11     class StartEndComparer : IComparer<Interval>

12     {

13         public static StartEndComparer Default = new StartEndComparer();

14         public int Compare(Interval v1, Interval v2)

15         {

16             if (v1.start == v2.start) return v1.end - v2.end;

17             return v1.start - v2.start;

18         }

19     }

20     public class IntervalComparison

21     {

22         public static int StartEnd(Interval v1, Interval v2)

23         {

24             if (v1.start == v2.start) return v1.end - v2.end;

25             return v1.start - v2.start;

26         }

27     }

28     public List<Interval> Merge(IList<Interval> intervals) {

29         

30         List<Interval> intervalsCopy = new List<Interval>(intervals.ToArray());

31         Comparison<Interval> StartEndComparison = new Comparison<Interval>(IntervalComparison.StartEnd);

32         intervalsCopy.Sort(StartEndComparison);

33         //intervalsCopy.Sort(StartEndComparer.Default);

34         List<Interval> ans = new List<Interval>();

35         for (int i = 0; i < intervals.Count; i++) {

36             if (ans.Count == 0 || intervalsCopy[i].start > ans[ans.Count-1].end) ans.Add(intervalsCopy[i]);

37             else ans[ans.Count-1].end = Math.Max(ans[ans.Count-1].end, intervalsCopy[i].end);

38         }

39         return ans;

40     }

41 }
View Code

 

 

你可能感兴趣的:(LeetCode)