我在挣扎于codewars (称为范围提取)--它以递增的顺序获取整数列表,并以范围格式返回一个格式正确的字符串(重叠的单独间隔)。
示例解决方案:
([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns "-6,-3-1,3-5,7-11,14,15,17-20"
在我的解决方案中,我没有得到-6,-3-1,3-5,7-11,14,15,17-20
,而是得到了最后一个项目-6,1,5,11,15,20
。
我怎样才能提高我的解决方案?守则:
function solution(list){
let result=[]
for(let i=0;i<list.length;i++){
let e2=list[i]
let e1 = result[result.length-1]
if(e2-e1==1){
result[result.length-1]=e2
}
else{
result.push(e2 )
}
}
return result
}
console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]))
发布于 2021-11-27 20:05:32
您不需要以范围格式写入连续整数。相反,您只是将前面的结果替换为范围中的最后一项,这完全反映在您的解决方案中:
-6: this number has no "neighbors" so is fine
1: the final item in the first range
5: the final item in the second range
...
问题在于循环的内部逻辑。
总之,您需要一段时间而不是if,并且需要追加而不是替换:
function solution(list){
let result=[]
for(let i=0;i<list.length;i++){
//write first value in range to result
result.push(list[i].toString())
//if this is the last entry, we are done
if(i === list.length - 1){
break
}
//initialize variables
let e1 = list[i]
let e2 = list[i+1]
let isRange = false
//run thorugh array while we get consecutive numbers
while(e2-e1===1 && i < list.length-1){
//modify the OUTER LOOP index variable.
//This means when we return to the beginning of hte for loop,
// we will be at the beginning of the next range
i++
e1 = list[i]
e2 = list[i+1]
isRange = true
}
//if there were any consecutive numbers
if(isRange){
//rewrite the last entry in result as a range
result[result.length-1]+="-" + list[i].toString()
}
}
return result.toString()
}
console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]))
现在,您的外部循环只在整个数组中运行一次。内环将确保外部循环跳过列表中出现在范围内的任何项。最后,如果内循环找到了任何范围,它将重写条目作为正确的范围。
https://stackoverflow.com/questions/70135839
复制相似问题