-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00853-car_fleet.go
More file actions
49 lines (38 loc) · 788 Bytes
/
00853-car_fleet.go
File metadata and controls
49 lines (38 loc) · 788 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 853: Car Fleet
// https://leetcode.com/problems/car-fleet/
package main
import (
"fmt"
"sort"
)
type car struct {
p int
s int
}
// SOLUTION
func carFleet(target int, position []int, speed []int) int {
cars := []car{}
n := len(position)
for i:=0; i<n; i++ {
cars = append(cars, car{position[i], speed[i]})
}
sort.Slice(cars, func(i, j int) bool {
return cars[i].p < cars[j].p
})
s := []float64{}
for i:=0; i<n; i++ {
time := float64((target - cars[i].p) / cars[i].s)
for len(s)!=0 && time >= s[len(s)-1] {s = s[:len(s)-1]}
s = append(s, time)
}
return len(s);
}
func main() {
// INPUT
target := 12
position := []int{10,8,0,5,3}
speed := []int{2,4,1,1,3}
// OUTPUT
result := carFleet(target, position, speed)
fmt.Println(result)
}