首页 > 解决方案 > 从数组末尾查找第 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);

结果似乎通过了测试站点,但不是代码信号。

在新标签中打开下面的链接

挑战

测试仪

数组长度

标签: javascriptarrays

解决方案


您需要分析进入函数的输入。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];
    }
}

推荐阅读