就是求 区间覆盖的问题。
【x, y】
按x排序, 对y,二分找刚好大于它的x。
package solution // you can also use imports, for example: import "fmt" import "sort" // you can write to stdout for debugging purposes, e.g. // fmt.Println("this is a debug message") type interval struct { x, y int64 } func (i interval) String() string { return fmt.Sprintf("[%d, %d]", i.x, i.y) } type ByX []interval func (a ByX) Len() int { return len(a) } func (a ByX) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByX) Less(i, j int) bool { return a[i].x < a[j].x } func Solution(A []int) int { N := len(A) intervals := []interval{} for i, a := range(A) { intervals = append(intervals, interval{int64(i - a), int64(i + a)}) } sort.Sort(ByX(intervals)) //fmt.Println(intervals) count := 0 for i := 0; i < N - 1; i++ { target := intervals[i].y low, high := i + 1, N for ; low < high; { mid := low + ((high - low) >> 1) if intervals[mid].x <= target { low = mid + 1 } else { high = mid } } //fmt.Println("i: ", i, "##", intervals[i]) //fmt.Println("low: ", low) count += low - i - 1 //fmt.Println("count:", count) } return count }
原文地址:https://www.cnblogs.com/brayden/p/9027066.html
时间: 2024-10-18 11:06:07