Skip to content

Commit aea24be

Browse files
author
chen-shiwei
committed
feat: 134 greedy
1 parent dee3612 commit aea24be

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package _134_加油站
2+
3+
func canCompleteCircuit(gas []int, cost []int) int {
4+
l1 := len(gas)
5+
6+
for i := 0; i < l1; i++ {
7+
var ans = gas[i] - cost[i]
8+
idx := (i + 1) % l1
9+
for idx != i && ans > 0 {
10+
ans += gas[idx] - cost[idx]
11+
idx = (idx + 1) % l1
12+
}
13+
if ans >= 0 && idx == i {
14+
return i
15+
}
16+
}
17+
return -1
18+
}
19+
20+
func canCompleteCircuitWithGreedy(gas []int, cost []int) int {
21+
l := len(gas)
22+
var curSum, sum, idx int
23+
for i := 0; i < l; i++ {
24+
sum += gas[i] - cost[i]
25+
curSum += gas[i] - cost[i]
26+
if curSum < 0 {
27+
idx = i + 1
28+
curSum = 0
29+
}
30+
}
31+
if sum < 0 {
32+
return -1
33+
}
34+
35+
return idx
36+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package _134_加油站
2+
3+
import "testing"
4+
5+
func Test_canCompleteCircuit(t *testing.T) {
6+
type args struct {
7+
gas []int
8+
cost []int
9+
}
10+
tests := []struct {
11+
name string
12+
args args
13+
want int
14+
}{
15+
{name: `gas = [1,2,3,4,5]
16+
cost = [3,4,5,1,2]`, args: args{
17+
gas: []int{1, 2, 3, 4, 5},
18+
cost: []int{3, 4, 5, 1, 2},
19+
}, want: 3},
20+
}
21+
for _, tt := range tests {
22+
t.Run(tt.name, func(t *testing.T) {
23+
if got := canCompleteCircuitWithGreedy(tt.args.gas, tt.args.cost); got != tt.want {
24+
t.Errorf("canCompleteCircuit() = %v, want %v", got, tt.want)
25+
}
26+
})
27+
}
28+
}

0 commit comments

Comments
 (0)