首页 > 解决方案 > 需要帮助来解决具有挑战性的数据结构问题

问题描述

我遇到了这个问题,给定一个整数数组,判断整数序列是否将从左、右或死端退出数组。您从左侧输入数组并在指定方向移动 N 个索引(其中 N 是整数的值)(正为右,负为左)

Examples
[1,1,1] -> Exits Right
[1,-2]=> Exits Left
[2,0,-1]-> Deadends
[2,5,1,-2,0]-> Exits Right

我想到的一种解决方案是,如果所有整数的值都是正数,那么退出右或退出左。但是,此解决方案并未涵盖所有场景。我需要帮助来解决这个问题。

标签: arraysdata-structures

解决方案


你可以这样做:

  • 创建一个变量来保存索引位置并用第一个值初始化它
  • 遍历数组并在每次迭代时,index通过添加指向索引的值来计算新值。
  • 在循环结束时,检查:
    • Right: 如果index>= array.length`
    • Left: 如果index < 0
    • Deadend: 如果index在范围内

基于此,以下是使用 Javascript 的示例:

function printDirection(arr) {
  let index = arr[0];
  for (let i = 1; i < arr.length; i++) {
    /**
     * Below condition covers following cases:
     * 1. If the value is undefined. This will happen if index is out of bound
     * 2. If value is 0. In this case, `index` will never change and remaining iterations can be skipped
     */
    if (!arr[index]) break;
    index += arr[index]
  }
  if (index >= arr.length) {
    console.log('Exit Right')
  } else if (index < 0) {
    console.log('Exit Left')
  } else {
    console.log('Deadend')
  }
}

const data = [
  [1, 1, 1],
  [1, -2],
  [2, 0, -1],
  [2, 5, 1, -2, 0],
]
data.forEach((arr) => printDirection(arr))


推荐阅读