>  기사  >  웹 프론트엔드  >  Leetcode #메모이즈

Leetcode #메모이즈

Patricia Arquette
Patricia Arquette원래의
2024-10-02 06:43:30491검색

fn 함수가 주어지면 해당 함수의 메모된 버전을 반환합니다.

memoized 함수는 동일한 입력으로 두 번 호출되지 않는 함수입니다. 대신 캐시된 값을 반환합니다.

sum, fib, 계승의 3가지 입력 함수가 있다고 가정할 수 있습니다.

sum은 두 개의 정수 a와 b를 허용하고 b를 반환합니다. a != b인 인수 (b, a)에 대해 값이 이미 캐시된 경우 인수 (a, b)에 사용할 수 없다고 가정합니다. 예를 들어 인수가 (3, 2)와 (2, 3)인 경우 별도의 두 호출을 수행해야 합니다.
fib는 단일 정수 n을 받아들이고 n 계승은 단일 정수 n을 받아들이고 n

예 1:

입력:

fnName = "sum"
actions = ["call","call","getCallCount","call","getCallCount"]
values = [[2,2],[2,2],[],[1,2],[]]

출력: [4,4,1,3,2]
설명:

const sum = (a, b) => a + b;
const memoizedSum = memoize(sum);
memoizedSum(2, 2); // "call" - returns 4. sum() was called as (2, 2) was not seen before.
memoizedSum(2, 2); // "call" - returns 4. However sum() was not called because the same inputs were seen before.
// "getCallCount" - total call count: 1
memoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before.
// "getCallCount" - total call count: 2

예 2:

입력:

fnName = "factorial"
actions = ["call","call","call","getCallCount","call","getCallCount"]
values = [[2],[3],[2],[],[3],[]]

출력: [2,6,2,2,6,2]
설명:

const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));
const memoFactorial = memoize(factorial);
memoFactorial(2); // "call" - returns 2.
memoFactorial(3); // "call" - returns 6.
memoFactorial(2); // "call" - returns 2. However factorial was not called because 2 was seen before.
// "getCallCount" - total call count: 2
memoFactorial(3); // "call" - returns 6. However factorial was not called because 3 was seen before.
// "getCallCount" - total call count: 2

예 3:

입력:

fnName = "fib"
actions = ["call","getCallCount"]
values = [[5],[]]

출력: [8,1]
설명:

fib(5) = 8 // "call"
// "getCallCount" - total call count: 1

제약조건:

> 0 <= a, b <= 105
> 1 <= n <= 10
> 0 <= actions.length <= 105
> actions.length === values.length

actions[i]는 "call" 및 "getCallCount" 중 하나입니다
fnName은 "sum", "factorial", "fib" 중 하나입니다

솔루션

Leetcode #Memoize

JavaScript 애플리케이션을 계속 개발하고 최적화할 때 메모의 힘을 기억하세요. 메모하기에 적합한 기능을 식별하고 적절한 캐싱 전략을 구현함으로써 상당한 성능 향상을 얻을 수 있으며 고객을 위한 보다 원활하고 응답성이 뛰어난 사용자 경험을 만들 수 있습니다.

이 글이 도움이 되었으면 좋겠습니다. 글이 마음에 드셨다면 좋아요를 남겨주시고, 궁금한 점은 댓글로 남겨주세요. 오늘은 여기까지입니다.

위 내용은 Leetcode #메모이즈의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.