codility problem - NumberOfDiscIntersections
Posted brayden
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了codility problem - NumberOfDiscIntersections相关的知识,希望对你有一定的参考价值。
就是求 区间覆盖的问题。
【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 }
以上是关于codility problem - NumberOfDiscIntersections的主要内容,如果未能解决你的问题,请参考以下文章
Codility 任务 TapEquilibrium 正确性仅为 33%
Solution to Triangle by Codility
CountNonDivisible - Codility 训练任务