LeetCode 题解工作台

数组原型对象的最后一个元素

请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。 你可以假设数组是 JSON.parse 的输出结果。 示例 1 : 输入: nums = [null, {}, 3] 输出: 3 解释 :调用…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · 数组·prototype·last·core·interview·pattern

bolt

答案摘要

declare global { interface Array<T> {

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·prototype·last·core·interview·pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。

你可以假设数组是 JSON.parse 的输出结果。

 

示例 1 :

输入:nums = [null, {}, 3]
输出:3
解释:调用 nums.last() 后返回最后一个元素: 3。

示例 2 :

输入:nums = []
输出:-1
解释:因为此数组没有元素,所以应该返回 -1。

 

提示:

  • arr 是一个有效的 JSON 数组
  • 0 <= arr.length <= 1000
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
declare global {
    interface Array<T> {
        last(): T | -1;
    }
}

Array.prototype.last = function () {
    return this.length ? this.at(-1) : -1;
};

/**
 * const arr = [1, 2, 3];
 * arr.last(); // 3
 */

export {};
speed

复杂度分析

指标
时间complexity is O(1) because accessing the last index is constant. Space complexity is O(1) as no additional storage is required beyond the function itself.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you handle empty arrays explicitly to avoid undefined?

  • question_mark

    Are you modifying Array.prototype directly or using a helper function?

  • question_mark

    Can your last() method handle arrays with mixed types, including objects and nulls?

warning

常见陷阱

外企场景
  • error

    Accessing this[this.length] instead of this[this.length-1] causing undefined.

  • error

    Not checking for empty arrays and returning undefined instead of -1.

  • error

    Mutating the array inside last(), which breaks immutability expectations.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implement last(n) to return the last n elements instead of just one.

  • arrow_right_alt

    Create a first() method alongside last() to retrieve the first element safely.

  • arrow_right_alt

    Support chaining by returning a wrapper object with last() and other utility methods.

help

常见问题

外企场景

数组原型对象的最后一个元素题解:数组·prototype·last·core·… | LeetCode #2619 简单