LeetCode 题解工作台

计数器

给定一个整型参数 n ,请你编写并返回一个 counter 函数。这个 counter 函数最初返回 n ,每次调用它时会返回前一个值加 1 的值 ( n , n + 1 , n + 2 ,等等)。 示例 1: 输入: n = 10 ["call","call","call"] 输出: [10,11…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Counter core interview pattern

bolt

答案摘要

function createCounter(n: number): () => number { let i = n;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Counter core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整型参数 n,请你编写并返回一个 counter 函数。这个 counter 函数最初返回 n,每次调用它时会返回前一个值加 1 的值 ( nn + 1n + 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 <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function createCounter(n: number): () => number {
    let i = n;
    return function () {
        return i++;
    };
}

/**
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

计数器题解:Counter core interview … | LeetCode #2620 简单