跳至主要內容

2695. 包装数组


2695. 包装数组

🟢   🔗 力扣open in new window LeetCodeopen in new window

题目

Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features:

  • When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

Example 1:

Input: nums = [[1,2],[3,4]], operation = "Add"

Output: 10

Explanation:

const obj1 = new ArrayWrapper([1,2]);

const obj2 = new ArrayWrapper([3,4]);

obj1 + obj2; // 10

Example 2:

Input: nums = [[23,98,42,70]], operation = "String"

Output: "[23,98,42,70]"

Explanation:

const obj = new ArrayWrapper([23,98,42,70]);

String(obj); // "[23,98,42,70]"

Example 3:

Input: nums = [[],[]], operation = "Add"

Output: 0

Explanation:

const obj1 = new ArrayWrapper([]);

const obj2 = new ArrayWrapper([]);

obj1 + obj2; // 0

Constraints:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • Note: nums is the array passed to the constructor

题目大意

创建一个名为 ArrayWrapper 的类,它在其构造函数中接受一个整数数组作为参数。该类应具有以下两个特性:

  • 当使用 + 运算符将两个该类的实例相加时,结果值为两个数组中所有元素的总和。
  • 当在实例上调用 String() 函数时,它将返回一个由逗号分隔的括在方括号中的字符串。例如,[1,2,3]

提示:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • 注意:nums 是传递给构造函数的数组。

解题思路

  1. 定义包装类:创建一个名为 ArrayWrapper 的类,接收一个数组作为构造参数。
  2. 实现基本方法
    • toString:返回数组的字符串表示形式。
    • valueOf:返回数组元素的总和。
  3. 重载运算符:使用 valueOf 来支持加法操作,确保可以直接与数字进行相加。

复杂度分析

  • 时间复杂度O(n),其中 n 是数组的长度,求和和获取长度操作需要遍历数组。
  • 空间复杂度O(1),只使用了固定的额外空间。

代码

/**
 * @param {number[]} nums
 * @return {void}
 */
var ArrayWrapper = function (nums) {
	this.arr = arr; // 存储数组
};

/**
 * @return {number}
 */
ArrayWrapper.prototype.valueOf = function () {
	return this.arr.reduce((acc, cur) => acc + cur, 0); // 返回数组元素的总和
};

/**
 * @return {string}
 */
ArrayWrapper.prototype.toString = function () {
	return JSON.stringify(this.arr); // 返回数组的字符串表示
};

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */