kotlin - 如何使用功能性和更高效的风格重新编写此代码?
问题描述
描述:
给定一个整数列表,例如[2,2,0,2,0,3,1,1]
. 将其视为随时间变化的某些材料的库存。假设索引从 1 开始。在时间单位 1 我们有两个单位的材料,在时间单位 6 我们有 3 个单位,依此类推。
我们得到一个固定大小的容器。我们可以为一个时间索引填充一个单位的材料。
例如,如果容器的大小为 3,我们从时间索引 1 开始填充:
在时间索引 1 处,我们将填充一个单元(即使有 2 个单元可用)
在时间索引 2 处,我们还将填充 1 个单位
在时间索引 3 处,由于库存为零,没有可填充的内容
在时间索引 4 处,我们将填充一个单元。因此容器已满
目的是回答每个可能的时间索引的问题。
PS:当可用单位为零时,我们不允许开始填充
我的尝试:
fun givenStartComputeLength(start: Int, containerSize : Int, table: List<Int>) : Int{
var howLongItWillTake = -1
var cumulated = 0
for (index in start until table.size){
if (table[index] > 0){
cumulated += 1
}
if (cumulated == containerSize){
howLongItWillTake = index - start + 1
break
}
}
return howLongItWillTake
}
fun startsToLengths(containerSize : Int, table: List<Int>) : Map<Int,Int>{
val startToLength = mutableMapOf<Int,Int>()
for (index in 1..table.size-containerSize+1){
if (table[index-1] != 0){
val length = givenStartComputeLength(index-1, containerSize, table)
startToLength[index] = length
}
}
return startToLength
}
fun main() {
val table = listOf(2,2,0,2,0,3,1,1)
//Manual resolution :
/// starts 1 ---> ends at 4 --> length 4 (i.e it will take 4 time units)
/// starts 2 --> ends at 6 --> length 5
/// starts 4 --> ends at 7 --> length 4
// starts 6 ---> ends at 8 --> length 3
println(startsToLengths(3,table)) // output {1=4, 2=5, 4=4, 6=3}
val table2 = listOf(2,2,0,2,0,3,0,1)
println(startsToLengths(3,table2)) //Output{1=4, 2=5, 4=5, 6=-1}
}
问题:它可以工作,但我认为我写的既不是 kotlin 风格的代码,也不是高效的代码。我认为更实用的时尚会更好。有什么帮助吗?
解决方案
我认为制作算法的主要思想是 O(table.size),因为现在它是 O(table.size ** 2)。我们可以只使用上一步的结果来计算下一步的结果,这样可以节省我们的努力。
Playground有链接 :
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
println("Hello, world!!!")
fun startsToLengths(containerSize : Int, table: List<Int>) : Map<Int,Int> {
val startToLength = mutableMapOf<Int,Int>()
var s = 0
var e = 0
val l = table.size-containerSize + 1
var count = 0
var len = 0
while (s < l) {
while (table[s] == 0 && s < l ) {
s++
len--
}
if (s == l) { break }
if (e < l ) { e = l }
while (e < table.size) {
if (table[e] > 0) { count++ }
e++
len++
if (count == containerSize) {
startToLength[s+1] = len
if (table[s] > 0) { count-- }
s++
len--
break
} else if (e == table.size) {
startToLength[s+1] = -1
s = l
break
}
}
}
return startToLength
}
val table = listOf(2,2,0,2,0,3,1,1)
println(startsToLengths(3,table))
}
推荐阅读
- protocol-buffers - 从命令行为大量 protoc 文件运行 protoc 编译器
- javascript - RFC2822 日期的 Moment.js 转换
- reactjs - React 应用程序卡在“正在启动开发服务器”
- oracle - 如果子查询没有返回行,如何使用 IN 子查询获取所有行
- laravel-5 - 提交时如何获取Select2的选定项的值?
- c - 函数调用的参数中可以使用后自增运算符吗?在 C?
- python - 如何在函数中编写条件以发表此评论 Python
- ansible - 寄存器变量索引结果上的ansible循环
- winpcap - pcap4j+winpcap 我应该手动运行 rpcapd.exe 吗?
- javascript - 确定 XPath 以检索特定属性数据的方法