package q986 import "slices" type listElem struct { x int listId int8 // 0, 1 isStart bool } func intervalIntersection(firstList [][]int, secondList [][]int) [][]int { locations := make([]listElem, 0, len(firstList)*2+len(secondList)*2) for i := range firstList { locations = append( locations, listElem{x: firstList[i][0], listId: 0, isStart: true}, listElem{x: firstList[i][1], listId: 0, isStart: false}, ) } for i := range secondList { locations = append( locations, listElem{x: secondList[i][0], listId: 1, isStart: true}, listElem{x: secondList[i][1], listId: 1, isStart: false}, ) } slices.SortFunc(locations, func(a, b listElem) int { if a.x != b.x { return a.x - b.x } if a.isStart { return -1 } return 1 }) ret := [][]int{} start := 0 isA, isB := false, false for _, loc := range locations { if loc.isStart { start = loc.x switch loc.listId { case 0: isA = true default: isB = true } } else { if isA && isB { ret = append(ret, []int{start, loc.x}) } switch loc.listId { case 0: isA = false default: isB = false } } } return ret } var _ = intervalIntersection