簡體   English   中英

從數組的末尾找到第 n 個元素

[英]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.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;
    }
}
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM