[英]Find an nth element from the end of an array
我从 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);
结果似乎通过了测试站点,但不是codesignal。
在新标签中打开下面的链接
您需要分析进入函数的输入。 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];
}
}
这里的技巧是在指示单链表接口的注释中。
// 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;
}
}
function nthElementFromTheEnd(l, n) {
var input = l;
var rev= input.reverse();
let value = rev[n-1];
if(value){
return value;
}
else
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.