Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit35d1c14

Browse files
authored
Added tasks 2619-2623
1 parent413de2c commit35d1c14

File tree

15 files changed

+409
-0
lines changed

15 files changed

+409
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2619\. Array Prototype Last
2+
3+
Easy
4+
5+
Write code that enhances all arrays such that you can call the`array.last()` method on any array and it will return the last element. If there are no elements in the array, it should return`-1`.
6+
7+
You may assume the array is the output of`JSON.parse`.
8+
9+
**Example 1:**
10+
11+
**Input:** nums =[null, {}, 3]
12+
13+
**Output:** 3
14+
15+
**Explanation:** Calling nums.last() should return the last element: 3.
16+
17+
**Example 2:**
18+
19+
**Input:** nums =[]
20+
21+
**Output:** -1
22+
23+
**Explanation:** Because there are no elements, return -1.
24+
25+
**Constraints:**
26+
27+
*`0 <= arr.length <= 1000`
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// #Easy #2023_08_31_Time_41_ms_(98.99%)_Space_42_MB_(96.92%)
2+
3+
declare global{
4+
interfaceArray<T>{
5+
last():T|-1;
6+
}
7+
}
8+
9+
Array.prototype.last=function(){//NOSONAR
10+
returnthis.length!==0 ?this[this.length-1] :-1
11+
}
12+
13+
/*
14+
* const arr = [1, 2, 3];
15+
* arr.last(); // 3
16+
*/
17+
18+
export{}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2620\. Counter
2+
3+
Easy
4+
5+
Given an integer`n`, return a`counter` function. This`counter` function initially returns`n` and then returns 1 more than the previous value every subsequent time it is called (`n`,`n + 1`,`n + 2`, etc).
6+
7+
**Example 1:**
8+
9+
**Input:** n = 10["call","call","call"]
10+
11+
**Output:**[10,11,12]
12+
13+
**Explanation:**
14+
15+
counter() = 10 // The first time counter() is called, it returns n.
16+
17+
counter() = 11 // Returns 1 more than the previous time.
18+
19+
counter() = 12 // Returns 1 more than the previous time.
20+
21+
**Example 2:**
22+
23+
**Input:** n = -2["call","call","call","call","call"]
24+
25+
**Output:**[-2,-1,0,1,2]
26+
27+
**Explanation:** counter() initially returns -2. Then increases after each sebsequent call.
28+
29+
**Constraints:**
30+
31+
*`-1000<= n <= 1000`
32+
*`At most 1000 calls to counter() will be made`
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// #Easy #2023_08_31_Time_43_ms_(98.60%)_Space_42.2_MB_(91.27%)
2+
3+
functioncreateCounter(n:number):()=>number{
4+
constfun=function(){
5+
n++
6+
returnn-1
7+
}
8+
returnfun
9+
}
10+
11+
/*
12+
* const counter = createCounter(10)
13+
* counter() // 10
14+
* counter() // 11
15+
* counter() // 12
16+
*/
17+
18+
export{createCounter}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2621\. Sleep
2+
3+
Easy
4+
5+
Given a positive integer`millis`, write an asynchronous function that sleeps for`millis` milliseconds. It can resolve any value.
6+
7+
**Example 1:**
8+
9+
**Input:** millis = 100
10+
11+
**Output:** 100
12+
13+
**Explanation:** It should return a promise that resolves after 100ms. let t = Date.now(); sleep(100).then(() => { console.log(Date.now() - t); // 100 });
14+
15+
**Example 2:**
16+
17+
**Input:** millis = 200
18+
19+
**Output:** 200
20+
21+
**Explanation:** It should return a promise that resolves after 200ms.
22+
23+
**Constraints:**
24+
25+
*`1 <= millis <= 1000`
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// #Easy #2023_08_31_Time_40_ms_(99.59%)_Space_42.3_MB_(77.98%)
2+
3+
asyncfunctionsleep(millis:number):Promise<void>{
4+
awaitnewPromise(resolve=>setTimeout(resolve,millis));
5+
}
6+
7+
/*
8+
* let t = Date.now()
9+
* sleep(100).then(() => console.log(Date.now() - t)) // 100
10+
*/
11+
12+
export{sleep}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
2622\. Cache With Time Limit
2+
3+
Medium
4+
5+
Write a class that allows getting and setting key-value pairs, however a**time until expiration** is associated with each key.
6+
7+
The class has three public methods:
8+
9+
`set(key, value, duration)`: accepts an integer`key`, an integer`value`, and a`duration` in milliseconds. Once the`duration` has elapsed, the key should be inaccessible. The method should return`true` if the same un-expired key already exists and`false` otherwise. Both the value and duration should be overwritten if the key already exists.
10+
11+
`get(key)`: if an un-expired key exists, it should return the associated value. Otherwise it should return`-1`.
12+
13+
`count()`: returns the count of un-expired keys.
14+
15+
**Example 1:**
16+
17+
**Input:**["TimeLimitedCache", "set", "get", "count", "get"][[],[1, 42, 100],[1],[],[1]][0, 0, 50, 50, 150]
18+
19+
**Output:**[null, false, 42, 1, -1]
20+
21+
**Explanation:**
22+
23+
At t=0, the cache is constructed.
24+
25+
At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned.
26+
27+
At t=50, key=1 is requested and the value of 42 is returned.
28+
29+
At t=50, count() is called and there is one active key in the cache.
30+
31+
At t=100, key=1 expires.
32+
33+
At t=150, get(1) is called but -1 is returned because the cache is empty.
34+
35+
**Example 2:**
36+
37+
**Input:**["TimeLimitedCache", "set", "set", "get", "get", "get", "count"][[],[1, 42, 50],[1, 50, 100],[1],[1],[1],[]][0, 0, 40, 50, 120, 200, 250]
38+
39+
**Output:**[null, false, true, 50, 50, -1]
40+
41+
**Explanation:**
42+
43+
At t=0, the cache is constructed.
44+
45+
At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned.
46+
47+
At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten.
48+
49+
At t=50, get(1) is called which returned 50. At t=120, get(1) is called which returned 50.
50+
51+
At t=140, key=1 expires. At t=200, get(1) is called but the cache is empty so -1 is returned.
52+
53+
At t=250, count() returns 0 because the cache is empty.
54+
55+
**Constraints:**
56+
57+
* <code>0 <= key <= 10<sup>9</sup></code>
58+
* <code>0 <= value <= 10<sup>9</sup></code>
59+
*`0 <= duration <= 1000`
60+
*`total method calls will not exceed 100`
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// #Medium #2023_08_31_Time_51_ms_(94.82%)_Space_42.2_MB_(94.26%)
2+
3+
classTimeLimitedCache{
4+
privatekeyMap:Map<number,any>
5+
constructor(){
6+
this.keyMap=newMap<number,any>()
7+
}
8+
9+
set(key:number,value:number,duration:number):boolean{
10+
letexisted:boolean=this.keyMap.has(key)
11+
if(existed)clearTimeout(this.keyMap.get(key).clearRef)
12+
13+
this.keyMap.set(key,{
14+
value,
15+
clearRef:setTimeout(()=>{
16+
this.keyMap.delete(key)
17+
},duration),
18+
})
19+
returnexisted
20+
}
21+
22+
get(key:number):number{
23+
returnthis.keyMap.has(key) ?this.keyMap.get(key).value :-1
24+
}
25+
26+
count():number{
27+
returnthis.keyMap.size
28+
}
29+
}
30+
31+
/*
32+
* Your TimeLimitedCache object will be instantiated and called as such:
33+
* var obj = new TimeLimitedCache()
34+
* obj.set(1, 42, 1000); // false
35+
* obj.get(1) // 42
36+
* obj.count() // 1
37+
*/
38+
39+
export{TimeLimitedCache}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
2623\. Memoize
2+
3+
Medium
4+
5+
Given a function`fn`, return a**memoized** version of that function.
6+
7+
A**memoized**function is a function that will never be called twice with the same inputs. Instead it will return a cached value.
8+
9+
You can assume there are**3**possible input functions:`sum`**,**`fib`**,**and`factorial`**.**
10+
11+
*`sum`accepts two integers`a` and`b` and returns`a + b`.
12+
*`fib`accepts a single integer`n` and returns`1` if`n <= 1` or`fib(n - 1) + fib(n - 2)` otherwise.
13+
*`factorial` accepts a single integer`n` and returns`1` if`n <= 1` or`factorial(n - 1) * n` otherwise.
14+
15+
**Example 1:**
16+
17+
**Input** "sum"["call","call","getCallCount","call","getCallCount"][[2,2],[2,2],[],[1,2],[]]
18+
19+
**Output:**[4,4,1,3,2]
20+
21+
**Explanation:**
22+
23+
const sum = (a, b) => a + b;
24+
25+
const memoizedSum = memoize(sum);
26+
27+
memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before.
28+
29+
memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before.
30+
31+
// Total call count: 1
32+
33+
memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before.
34+
35+
// Total call count: 2
36+
37+
**Example 2:**
38+
39+
**Input** "factorial"["call","call","call","getCallCount","call","getCallCount"][[2],[3],[2],[],[3],[]]
40+
41+
**Output:**[2,6,2,2,6,2]
42+
43+
**Explanation:**
44+
45+
const factorial = (n) => (n <= 1) ? 1 : (n\* factorial(n - 1));
46+
47+
const memoFactorial = memoize(factorial);
48+
49+
memoFactorial(2); // Returns 2.
50+
51+
memoFactorial(3); // Returns 6.
52+
53+
memoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before.
54+
55+
// Total call count: 2
56+
57+
memoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before.
58+
59+
// Total call count: 2
60+
61+
**Example 3:**
62+
63+
**Input** "fib"["call","getCallCount"][[5],[]]
64+
65+
**Output:**[8,1]
66+
67+
**Explanation:** fib(5) = 8 // Total call count: 1
68+
69+
**Constraints:**
70+
71+
* <code>0 <= a, b <= 10<sup>5</sup></code>
72+
*`1 <= n <= 10`
73+
* <code>at most 10<sup>5</sup> function calls</code>
74+
* <code>at most 10<sup>5</sup> attempts to access callCount</code>
75+
*`input function is sum, fib, or factorial`
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// #Medium #2023_08_31_Time_264_ms_(97.20%)_Space_109.2_MB_(32.97%)
2+
3+
typeFn=(...params:any)=>any
4+
5+
functionmemoize(fn:Fn):Fn{
6+
constmem_args:Map<string,any>=newMap<string,any>()
7+
returnfunction(...args){
8+
constargs_str=args.toString()
9+
if(mem_args.has(args_str)){
10+
returnmem_args.get(args_str)
11+
}
12+
13+
constresult=fn(...args)
14+
mem_args.set(args_str,result)
15+
returnresult
16+
}
17+
}
18+
19+
/*
20+
* let callCount = 0;
21+
* const memoizedFn = memoize(function (a, b) {
22+
* callCount += 1;
23+
* return a + b;
24+
* })
25+
* memoizedFn(2, 3) // 5
26+
* memoizedFn(2, 3) // 5
27+
* console.log(callCount) // 1
28+
*/
29+
30+
export{memoize}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// tslint:disable:no-magic-numbers
2+
import'src/main/java/g2601_2700/s2619_array_prototype_last/solution'
3+
import{expect,test}from'vitest'
4+
5+
test('last',()=>{
6+
letnums=[null,{},3].last()
7+
expect(nums).toEqual(3)
8+
})
9+
10+
test('last2',()=>{
11+
letnums=[].last()
12+
expect(nums).toEqual(-1)
13+
})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// tslint:disable:no-magic-numbers
2+
import{createCounter}from'src/main/java/g2601_2700/s2620_counter/solution'
3+
import{expect,test}from'vitest'
4+
5+
test('createCounter',()=>{
6+
constcounter=createCounter(10)
7+
expect(counter()).toEqual(10)
8+
expect(counter()).toEqual(11)
9+
expect(counter()).toEqual(12)
10+
})
11+
12+
test('createCounter2',()=>{
13+
constcounter=createCounter(-2)
14+
expect(counter()).toEqual(-2)
15+
expect(counter()).toEqual(-1)
16+
expect(counter()).toEqual(0)
17+
expect(counter()).toEqual(1)
18+
expect(counter()).toEqual(2)
19+
})

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp