可以使用HashMap来记录重复的数字。遍历数字列表,如果当前数字与上一个数字相同,则增加重复计数器。否则,将计数器和数字存储在HashMap中,并将计数器重置为1。最后,遍历HashMap并找到重复计数器的最大值,以及对应的数字,即为连续重复出现最多的数字。
以下是Kotlin代码示例:
fun main(args: Array) {
val nums = listOf(1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 5)
var prev = nums[0]
var count = 1
val repeatCountMap = HashMap()
for (i in 1 until nums.size) {
if (nums[i] == prev) {
count++
} else {
repeatCountMap[prev] = count
count = 1
prev = nums[i]
}
}
repeatCountMap[prev] = count // 处理最后一个数字
var maxRepeatCount = 0
var maxRepeatDigit = 0
for ((digit, repeatCount) in repeatCountMap) {
if (repeatCount > maxRepeatCount) {
maxRepeatCount = repeatCount
maxRepeatDigit = digit
}
}
println("连续重复出现最多的数字是 $maxRepeatDigit,出现次数为 $maxRepeatCount")
}