华为OD机试真题2023_Swift_100_找出通过车辆最多的
2023-03-21 本文已影响0人
雾中探雪
![](https://img.haomeiwen.com/i1043543/3cffa62c05f9dbae.png)
![](https://img.haomeiwen.com/i1043543/69bc385a1e2a9ce0.png)
![](https://img.haomeiwen.com/i1043543/a1bc0050066bd691.png)
![](https://img.haomeiwen.com/i1043543/063c873774192188.png)
// 找出通过车辆最多的颜色
func HW2023030() {
// 测试用例
// let inputStr = "0 1 2 1", k = 3
// let inputStr = "0 1 2 1", k = 2
// 开始代码
let inputStr = String(readLine()!)
let k = Int(readLine()!)!
let str = inputStr.replacingOccurrences(of: " ", with: "")
let inputArr = inputStr.components(separatedBy: " ").map { Int($0) ?? 0}
let len = inputArr.count - k + 1
var res = 0
for i in 0..<len {
let temp = String(str.dropFirst(i).prefix(k))
var resArr: [Int] = [0,0,0]
for j in temp {
if j == "0" {
resArr[0] += 1
}else if j == "1" {
resArr[1] += 1
}else if j == "2" {
resArr[2] += 1
}
}
res = max(res, resArr.max()!)
}
print(res)
}