首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何实现堆栈数据结构的范围提取(代码战争任务)?

如何实现堆栈数据结构的范围提取(代码战争任务)?
EN

Stack Overflow用户
提问于 2021-11-27 14:50:55
回答 1查看 436关注 0票数 0

我在挣扎于codewars (称为范围提取)--它以递增的顺序获取整数列表,并以范围格式返回一个格式正确的字符串(重叠的单独间隔)。

示例解决方案:

代码语言:javascript
运行
复制
([-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

我怎样才能提高我的解决方案?守则:

代码语言:javascript
运行
复制
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]))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-27 20:05:32

您不需要以范围格式写入连续整数。相反,您只是将前面的结果替换为范围中的最后一项,这完全反映在您的解决方案中:

代码语言:javascript
运行
复制
-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,并且需要追加而不是替换:

代码语言:javascript
运行
复制
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]))

现在,您的外部循环只在整个数组中运行一次。内环将确保外部循环跳过列表中出现在范围内的任何项。最后,如果内循环找到了任何范围,它将重写条目作为正确的范围。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70135839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档