2665. 计数器 II
2665. 计数器 II
题目
Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.
The three functions are:
increment()increases the current value by 1 and then returns it.decrement()reduces the current value by 1 and then returns it.reset()sets the current value toinitand then returns it.
Example 1:
Input: init = 5, calls = ["increment","reset","decrement"]
Output: [6,5,4]
Explanation:
const counter = createCounter(5);
counter.increment(); // 6
counter.reset(); // 5
counter.decrement(); // 4
Example 2:
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]
Output: [1,2,1,0,0]
Explanation:
const counter = createCounter(0);
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
counter.reset(); // 0
counter.reset(); // 0
Constraints:
-1000 <= init <= 10000 <= calls.length <= 1000calls[i]is one of "increment", "decrement" and "reset"
题目大意
请你写一个函数 createCounter。这个函数接收一个初始的整数值 init。并返回一个包含三个函数的对象。
这三个函数是:
increment()将当前值加 1 并返回。decrement()将当前值减 1 并返回。reset()将当前值设置为init并返回。
提示:
-1000 <= init <= 10000 <= calls.length <= 1000calls[i]是 “increment”、“decrement” 和 “reset” 中的一个
解题思路
可以使用闭包来保存计数器的当前值,并且每次调用 increment、decrement 和 reset 时,访问闭包内的计数器值。闭包可以让在外部无法直接修改计数器的值,同时确保这三个操作都能正确地修改和访问这个值。
- 用一个变量
current来保存初始值,并且在闭包中维护这个值。 increment:每次调用时,将current增加 1 并返回新的值。decrement:每次调用时,将current减少 1 并返回新的值。reset:将current重置为初始值,并返回重置后的值。
复杂度分析
- 时间复杂度:
O(1),每个操作只对一个数字进行加减或赋值。 - 空间复杂度:
O(1),只需要存储一个current和init变量。
代码
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function (init) {
let current = init;
return {
increment: () => ++current,
decrement: () => --current,
reset: () => {
current = init;
return current;
}
};
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 2620 | 计数器 | [✓] | 🟢 | 🀄️ 🔗 |
