雷火笔试第二题到底怎么做?
第二题换了两种语言都是43%通过率
下面是我的Go和Python代码
package main import ( "fmt" "sort" ) func solution2(Hp, LHp, UHp, N int, attacks []int) int { result := 0 sort.Sort(sort.Reverse(sort.IntSlice(attacks))) //For DEBUG //path := make([]int, 0) //defer func() { // fmt.Println(path) //}() for _, atk := range attacks { for { atkedHp := Hp - atk if atkedHp > UHp { //For DEBUG //path = append(path, atk) result++ Hp -= atk } else if LHp <= atkedHp && atkedHp <= UHp { result++ //For DEBUG //path = append(path, atk) return result } else if atkedHp < LHp { break } } } return 0 } func main() { M := 0 fmt.Scan(&M) for m := 0; m < M; m++ { Hp, LHp, UHp, N := 0, 0, 0, 0 fmt.Scan(&Hp, &LHp, &UHp, &N) attacks := make([]int, N) for i := range attacks { atk := 0 fmt.Scan(&atk) attacks[i] = atk } fmt.Println(solution2(Hp, LHp, UHp, N, attacks)) } }
# -*-coding:utf-8-*- # coding=utf-8 import sys def solution2( Hp, LHp, UHp, attacks): result = 0 attacks.sort(reverse=True) for atk in attacks: while True: atkedHp = Hp - atk if atkedHp > UHp: result += 1 Hp -= atk elif LHp <= atkedHp and atkedHp <= UHp: result += 1 return result elif atkedHp < LHp: break return 0 if __name__ == "__main__": # 读取第一行的n n = int(sys.stdin.readline().strip()) for i in range(n): # 读取每一行 line = sys.stdin.readline().strip() # 把每一行的数字分隔后转化成int列表 values = list(map(int, line.split())) Hp, LHp, UHp, N = values[0], values[1], values[2], values[3] line = sys.stdin.readline().strip() # 把每一行的数字分隔后转化成int列表 attacks = list(map(int, line.split())) print(solution2( Hp, LHp, UHp, attacks))