|
| 1 | +type PointEntry struct { |
| 2 | + dist int |
| 3 | + x int |
| 4 | + y int |
| 5 | +} |
| 6 | + |
| 7 | +type PointHeap []*PointEntry |
| 8 | + |
| 9 | +func (h PointHeap) Len() int { return len(h) } |
| 10 | +func (h PointHeap) Less(i, j int) bool { return h[i].dist < h[j].dist } |
| 11 | +func (h PointHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } |
| 12 | +func (h *PointHeap) Push(x interface{}) {*h = append(*h, x.(*PointEntry))} |
| 13 | +func (h *PointHeap) Pop() interface{} { |
| 14 | + old := *h |
| 15 | + n := len(old) |
| 16 | + x := old[n-1] |
| 17 | + *h = old[0 : n-1] |
| 18 | + return x |
| 19 | +} |
| 20 | + |
| 21 | +const X = 0 |
| 22 | +const Y = 1 |
| 23 | +func kClosest(points [][]int, k int) [][]int { |
| 24 | + _pts := make([]*PointEntry, 0, len(points)) |
| 25 | + for _, point := range points { |
| 26 | + dist := (pow(abs(point[X] - 0), 2) + pow(abs(point[Y] - 0), 2)) |
| 27 | + _pts = append(_pts, &PointEntry{dist: dist, x: point[X], y: point[Y]}) |
| 28 | + } |
| 29 | + pts := PointHeap(_pts) |
| 30 | + |
| 31 | + res := make([][]int, 0) |
| 32 | + heap.Init(&pts) |
| 33 | + for i := 0; i < k; i++ { |
| 34 | + pointEntry := heap.Pop(&pts).(*PointEntry) |
| 35 | + res = append(res, []int{pointEntry.x, pointEntry.y}) |
| 36 | + } |
| 37 | + return res |
| 38 | +} |
| 39 | + |
| 40 | +func abs(a int) int { |
| 41 | + if a < 0 { |
| 42 | + return -a |
| 43 | + } |
| 44 | + return a |
| 45 | +} |
| 46 | + |
| 47 | +func pow(x, n int) int { |
| 48 | + if n == 0 { |
| 49 | + return 1 |
| 50 | + } else if n == 1 { |
| 51 | + return x |
| 52 | + } else { |
| 53 | + return pow(x, n/2) * pow(x, (n + 1)/2) |
| 54 | + } |
| 55 | +} |
0 commit comments