LeetCode 题解工作台
计数器
给定一个整型参数 n ,请你编写并返回一个 counter 函数。这个 counter 函数最初返回 n ,每次调用它时会返回前一个值加 1 的值 ( n , n + 1 , n + 2 ,等等)。 示例 1: 输入: n = 10 ["call","call","call"] 输出: [10,11…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Counter core interview pattern
答案摘要
function createCounter(n: number): () => number { let i = n;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Counter core interview pattern 题型思路
题目描述
给定一个整型参数 n,请你编写并返回一个 counter 函数。这个 counter 函数最初返回 n,每次调用它时会返回前一个值加 1 的值 ( n , n + 1 , n + 2 ,等等)。
示例 1:
输入: n = 10 ["call","call","call"] 输出:[10,11,12] 解释: counter() = 10 // 第一次调用 counter(),返回 n。 counter() = 11 // 返回上次调用的值加 1。 counter() = 12 // 返回上次调用的值加 1。
示例 2:
输入: n = -2 ["call","call","call","call","call"] 输出:[-2,-1,0,1,2] 解释:counter() 最初返回 -2。然后在每个后续调用后增加 1。
提示:
-1000 <= n <= 10000 <= calls.length <= 1000calls[i] === "call"
解题思路
方法一
function createCounter(n: number): () => number {
let i = n;
return function () {
return i++;
};
}
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) per call since each function invocation simply increments a variable. Space complexity is O(1) for storing the counter state within the closure. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checking for correct closure usage to maintain state
- question_mark
Ensuring sequential increment without external variables
- question_mark
Understanding how to return a function that preserves local state
常见陷阱
外企场景- error
Forgetting to use closure and losing the counter state
- error
Incrementing after returning instead of before leading to off-by-one errors
- error
Assuming counter must reset or using global variables incorrectly
进阶变体
外企场景- arrow_right_alt
Implement a counter that decrements instead of increments
- arrow_right_alt
Allow the counter to increment by a step value other than 1
- arrow_right_alt
Create multiple independent counters starting from different n values