arrays - 需要帮助来解决具有挑战性的数据结构问题
问题描述
我遇到了这个问题,给定一个整数数组,判断整数序列是否将从左、右或死端退出数组。您从左侧输入数组并在指定方向移动 N 个索引(其中 N 是整数的值)(正为右,负为左)
Examples
[1,1,1] -> Exits Right
[1,-2]=> Exits Left
[2,0,-1]-> Deadends
[2,5,1,-2,0]-> Exits Right
我想到的一种解决方案是,如果所有整数的值都是正数,那么退出右或退出左。但是,此解决方案并未涵盖所有场景。我需要帮助来解决这个问题。
解决方案
你可以这样做:
- 创建一个变量来保存索引位置并用第一个值初始化它
- 遍历数组并在每次迭代时,
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))
推荐阅读
- python - 不覆盖处理程序的路由层次结构
- angular - 错误:无法匹配任何路由。URL 段:'listproducts'
- regex - 正则表达式清理分隔符之前/之后没有文本的文本
- bash - 当出口 1 代码放在某个随机位置时,Bash 陷阱不会运行
- matlab - 用曲线函数定义的颜色图填充曲线下方的区域
- python - 如何使用 Json 发布多对多数据?
- php - 每个类和数组的 PHP
- c++ - 画线不起作用,可能是什么问题?
- android - 仅在 android studio 上不显示在设备上的编辑
- firebase - 如何比较 2 条记录的权限(Firestore-Rule)