LeetCode 题解工作台
数组原型对象的最后一个元素
请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。 你可以假设数组是 JSON.parse 的输出结果。 示例 1 : 输入: nums = [null, {}, 3] 输出: 3 解释 :调用…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · 数组·prototype·last·core·interview·pattern
答案摘要
declare global { interface Array<T> {
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·prototype·last·core·interview·pattern 题型思路
题目描述
请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。
你可以假设数组是 JSON.parse 的输出结果。
示例 1 :
输入:nums = [null, {}, 3]
输出:3
解释:调用 nums.last() 后返回最后一个元素: 3。
示例 2 :
输入:nums = [] 输出:-1 解释:因为此数组没有元素,所以应该返回 -1。
提示:
arr是一个有效的 JSON 数组0 <= arr.length <= 1000
解题思路
方法一
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 {};
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.