Skip to content

Latest commit

 

History

History
107 lines (78 loc) · 3.04 KB

2619.md

File metadata and controls

107 lines (78 loc) · 3.04 KB
title description keywords
2619. 数组原型对象的最后一个元素
LeetCode 2619. 数组原型对象的最后一个元素题解,Array Prototype Last,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
2619. 数组原型对象的最后一个元素
数组原型对象的最后一个元素
Array Prototype Last
解题思路

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

🟢 Easy  🔗 力扣 LeetCode

题目

Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.

You may assume the array is the output of JSON.parse.

Example 1:

Input: nums = [null, {}, 3]

Output: 3

Explanation: Calling nums.last() should return the last element: 3.

Example 2:

Input: nums = []

Output: -1

Explanation: Because there are no elements, return -1.

Constraints:

  • arr is a valid JSON array
  • 0 <= arr.length <= 1000

题目大意

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

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

示例 1 :

输入: nums = [null, {}, 3]

输出: 3

解释 :调用 nums.last() 后返回最后一个元素: 3。

示例 2 :

输入: nums = []

输出: -1

解释: 因为此数组没有元素,所以应该返回 -1。

提示:

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

解题思路

  1. 扩展 Array 原型:使用 Array.prototype 扩展数组的功能。
  2. 定义 last 方法:在该方法中,检查数组的长度。
    • 如果数组不为空,返回最后一个元素(使用 this[this.length - 1])。
    • 如果数组为空,返回 -1

复杂度分析

  • 时间复杂度O(1),因为访问数组的最后一个元素是常数时间操作。
  • 空间复杂度O(1),不需要额外的空间。

代码

/**
 * @return {null|boolean|number|string|Array|Object}
 */
Array.prototype.last = function () {
	return this.length ? this[this.length - 1] : -1;
};

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

相关题目

题号 标题 题解 标签 难度 力扣
2624 蜗牛排序 [✓] 🟠 🀄️ 🔗
2774 数组的上界 🔒 [✓] 🟢 🀄️ 🔗