【问题标题】:How can I prevent my while loop from causing an infinite loop?如何防止我的 while 循环导致无限循环?
【发布时间】:2021-08-03 23:41:42
【问题描述】:

我的 while 循环似乎导致了一个无限循环,但是当我单步执行它时,循环似乎适当地结束了。我没看到什么?在我看来,我的 else 应该向左迭代最终等于 2,然后 left 不再小于 right,它应该只返回 nums。

function removeDuplicates(nums) {

   let left = 0;
   let right = nums.length - 1;


   while (left < right) {
       if (nums[left] !== nums[left + 1]) {
          nums.splice(nums[left], 1)
          nums.push("_")
       } else {
           left++            
       }

     }

     return nums;
}

removeDuplicates([1,1,2])

我希望最终结果返回 [1,2,"_"]

【问题讨论】:

  • 即使它没有以无限循环结束,这种方法也不会删除重复项,只会删除立即重复。
  • nums[left] 不能作为 nums.splice() 的参数:它是一个值,而不是一个位置。
  • @MisterJojo 该值返回一个数字。数字可以用作位置。
  • 尝试removeDuplicates([10,10,20]) -> 没有10 索引元素
  • 啊,我明白你的意思了。我让它在我的浏览器中运行,但在 LeetCode 编辑器中失败了。

标签: javascript loops while-loop


【解决方案1】:

您的if 声明表述不当。我用while 交换它。你应该在nums[left] === nums[left + 1]nums[left] !== "_"时拼接并推入“_”,否则它会产生一个无限循环。嵌套while结束后不管怎样增加left

function removeDuplicates(nums) {

  let left = 0;
  let right = nums.length - 1;

  while (left < right) {
    while (nums[left] === nums[left + 1] && nums[left] !== "_") {
      nums.splice(left, 1)
      nums.push("_")
    }
    left++
  }

  return nums;
}

console.log(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))

【讨论】:

  • 这个解决方案有同样的问题。尝试更新您的答案以使用以下数字。 [0,0,1,1,1,2,2,3,3,4]。你会遇到同样的问题。
  • removeDuplicates([10,10,20]) 使用您的代码进行无限循环
  • @MisterJojo 我想 OP 想要使用按 +1 递增的排序数组。无论如何,最好只使用左变量索引拼接
【解决方案2】:

nums[left] == '_'nums[left +1] == '_' 时,你有一个无限循环
这样做...

const removeDuplicates = nums =>
  {
  for (let left=0; left< nums.length -1;) 
    {
    if (nums[left] === '_' ) break     // to avoid infinite loop
    if (nums[left] === nums[left +1]) 
      {
      nums.splice( left, 1) // not  splice( nums[left]
      nums.push('_')
      } 
    else left++  
    }
  return nums;
  }


console.log('1,1,2->', JSON.stringify(removeDuplicates([1,1,2])))
console.log('10,10,20->', JSON.stringify(removeDuplicates([10,10,20])))
console.log('0,0,1,1,1,2,2,3,3,4->', JSON.stringify(removeDuplicates([0,0,1,1,1,2,2,3,3,4])))
 
console.log( JSON.stringify(removeDuplicates(['a','a','b','b','b','c','c','d','d','e']))) 
.as-console-wrapper { max-height: 100% !important; top: 0 }
.as-console-row::after { display: none !important; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多