我从代码信号(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);
结果似乎通过了测试站点,但未通过代码信号。
在新标签下打开下面的链接
答案 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.next
和l.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;
}