LeetCode?启动!!!
简单题时间
题目链接:2660. 保龄球游戏的获胜者
func isWinner(player1 []int, player2 []int) (ans int) {
sum1, sum2 := 0, 0
for i := 0; i < len(player1); i++ {
if i >= 2 {
if player1[i-2] == 10 || player1[i-1] == 10 {
sum1 += player1[i]*2
} else {
sum1 += player1[i]
}
if player2[i-2] == 10 || player2[i-1] == 10 {
sum2 += player2[i]*2
} else {
sum2 += player2[i]
}
} else if i == 1 {
if player1[i-1] == 10 {
sum1 += player1[i]*2
} else {
sum1 += player1[i]
}
if player2[i-1] == 10 {
sum2 += player2[i]*2
} else {
sum2 += player2[i]
}
} else {
sum1 += player1[i]
sum2 += player2[i]
}
}
if sum1 > sum2 {
ans = 1
} else if sum1 < sum2 {
ans = 2
}
return ans
}
我有罪,我写了一坨屎山,这种求两个一模一样逻辑的题目,下次一定抽象出一个函数然后分别调用
func isWinner(player1 []int, player2 []int) int {
s1, s2 := score(player1), score(player2)
if s1 == s2 {
return 0
} else if s1 > s2 {
return 1
} else {
return 2
}
}
func score(player []int) int {
res := 0
for i, x := range player {
if i > 0 && player[i - 1] == 10 || i > 1 && player[i - 2] == 10 {
res += 2 * x
} else {
res += x
}
}
return res
}