从数组末尾查找第n个元素

时间:2020-01-25 00:34:36

标签: javascript arrays

我从代码信号(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);

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

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

challenge

tester

array length

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

这里的窍门是在注释中,指示单链列表的界面。

// Singly-linked lists are already defined with this interface:
// function ListNode(x) {
//   this.value = x;
//   this.next = null;
// }
//

因此,您需要使用l.nextl.value来导航并从链接列表中获取值。

这是一个可能的解决方案(未优化):

function nthElementFromTheEnd(l, n) {
    // find the length of the linked list
    let len = 1;
    let c = l;
    while (c.next) {
        len++;
        c = c.next;
    }

    if (n > len) {
        return -1
    }
    else {
        // iterate linked list and get desired value (len-n)
        let i = 0;
        while (i < len-n){
            l = l.next;
            i++;
        }

        return l.value;
    }
}

答案 2 :(得分:-1)

function nthElementFromTheEnd(l, n) {
var input = l;
var rev= input.reverse();
   let value = rev[n-1];
   if(value){
     return value;
   }
   else
    return -1;
}