javascript - 从数组末尾查找第 n 个元素
问题描述
我从 codesignal (nthelementfromtheend) 中查看了这个挑战,并将我的代码(如下)放在测试站点中
function nthElementFromTheEnd(l, n) {
if (n > l.length){
return -1;
}else{
// console.log();
let index = l.length - n;
// console.log(index);
// console.log(l[index]);
return l[index];
}
}
let l = [1, 2, 3, 4];
let n=7;
nthElementFromTheEnd(l, n);
结果似乎通过了测试站点,但不是代码信号。
在新标签中打开下面的链接
解决方案
您需要分析进入函数的输入。l
表示一个单链表。这在 JavaScript 中本机不存在,但它已使用对象重新创建,如评论所述:
// Singly-linked lists are already defined with this interface:
function ListNode(x) {
this.value = x;
this.next = null;
}
在第一个测试中,函数的输入如下所示:
ListNode {
value: 1,
next: ListNode {
value: 2,
next: ListNode {
value: 3,
next: null
}
}
}
所以这并不像从数组中返回特定索引那么简单,因为函数接收的不是数组而是对象。您必须导航数据结构,不断检查next
值。可能有更有效的方法可以做到这一点,但这里有一个至少通过 8 个样本测试的示例:
function nthElementFromTheEnd(l, n) {
let values = [];
let node = l;
while (node) {
values.push(node.value);
node = node.next;
}
let len = values.length;
if (n > len) {
return -1;
} else {
return values[len-n];
}
}
推荐阅读
- mysql - MySQL - 如果条件不唯一,则丢弃记录
- excel - Excel VBA - 如果在日期范围内,将表格行复制到另一个工作表
- batch-file - 比较数据的批处理脚本
- android - 在 JavaFXPorts 中更改 minSdkVersion 不起作用
- c++ - 字符串检查总是返回 false Palidrome
- django - Django:多重选择选项未在 html 中预填充
- sqlite - SQLite 连接多个表,按更少的 COUNT 排序
- python - 如何在 Python 中使用多个条件进行快速排序?
- excel - 复制到特定工作表:openpyxl - 使用 copy_worksheet 时忽略目标工作表
- glsl - Glslang 着色器“头”文件命名约定