【发布时间】:2021-01-19 13:22:50
【问题描述】:
我最近开始使用 HackerRank,并且正在尝试“按匹配销售”。在利用 Kotlin 的函数编程能力方面,我已经找到了一个我很满意的解决方案。但是,我没有得到预期的答案...
问题总结:
给定一个数组: -> 查找并返回对的总数。
即:
输入 -> [10, 20, 20, 10, 10, 30, 50, 10, 20]
对数 -> 3
这是我的代码和一些解释它的 cmets:
fun sockMerchant(n: Int, pile: Array<Int>): Int{
var count = 0
mutableMapOf<Int, Int>().withDefault { 0 }.apply {
// the [attempted] logic behind this piece of code here is
// that as we iterate through the list, the 'getOrPut()'
// function will return either the value for the given [key]
// or throw an exception if there is no such key
// in the map. However, since our map was created by
// [withDefault], the function resorts to its `defaultValue` <-> 0
// instead of throwing an exception.
for (e in values) {
// this simplifies our code and inserts a zero [+1] where needed.
// if (key exists)
// // return its associated value and MOD it:
// case: even -> increment counter
// else -> do nothing
// else if (key dne)
// // insert default value <-> [0] + 1
// ....
// ....
// ....
if (getOrPut(e, { getValue(e) + 1 } ) % 2 == 0) count++
}
}
return count
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val ar = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray()
val result = sockMerchant(n, ar)
println(result)
}
-- 任何帮助或提示都会在这里大有帮助:)
【问题讨论】:
-
n变量是什么意思? -
此外,您的示例输入中似乎只有两对。一对的定义是什么?
-
@AdamMillerchip - 我看到三对:(10, 10)、(10, 10) 和 (20, 20)。
-
@AdamMillerchip 列表的大小
-
@Todd 取决于对的定义,这就是我问的原因。但既然 OP 喜欢你的回答,我想你是对的。
标签: algorithm kotlin mutablemap