Created
April 4, 2019 06:27
-
-
Save Ahmah2009/8b39ec2097508169f2bfe90914f5f3b4 to your computer and use it in GitHub Desktop.
57. Insert Interval leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "sort" | |
/** | |
* Definition for an interval. | |
* type Interval struct { | |
* Start int | |
* End int | |
* } | |
*/ | |
func insert(intervals []Interval, newInterval Interval) []Interval { | |
intervals = append(intervals, newInterval) | |
sort.SliceStable(intervals, func(i, j int) bool { | |
return intervals[i].Start < intervals[j].Start | |
}) | |
return merge(intervals) | |
} | |
func merge(intervals []Interval) []Interval { | |
merged := []Interval{} | |
for _, interval := range intervals { | |
n := len(merged) | |
if n == 0 || merged[n-1].End < interval.Start { | |
merged = append(merged, interval) | |
} else { | |
merged[n-1].End = max(merged[n-1].End, interval.End) | |
} | |
} | |
return merged | |
} | |
func max(a, b int) int { | |
if a > b { | |
return a | |
} else { | |
return b | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment