Created
April 18, 2019 05:51
-
-
Save fr-xiaoli/e306ebc41480c2a772dc370d571568f4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package main | |
| import "sort" | |
| type Event struct { | |
| pos int | |
| eType int // 1 for start, -1 for end | |
| } | |
| type SortEvent []Event | |
| func (s SortEvent) Len() int { return len(s) } | |
| func (s SortEvent) Swap(i, j int) { s[i], s[j] = s[j], s[i] } | |
| func (s SortEvent) Less(i, j int) bool { | |
| e1 := s[i] | |
| e2 := s[j] | |
| if e1.pos == e2.pos && e1.eType != e2.eType { | |
| return e1.eType > e2.eType | |
| } | |
| return e1.pos < e2.pos | |
| } | |
| func main() { | |
| A := []int{1, 5, 2, 1, 4, 0} | |
| events := make([]Event, len(A) * 2) | |
| for idx, value := range A { | |
| events = append(events, | |
| Event{ idx - value, 1 }, | |
| Event{ idx + value, -1 }) | |
| } | |
| sort.Sort(SortEvent(events)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment