Skip to content

Commit 0a87bb1

Browse files
Merge pull request #2020 from 1lsang/main
[1lsang] WEEK 01 Solutions
2 parents 10e5a5b + 0e8f690 commit 0a87bb1

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

contains-duplicate/1lsang.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
function containsDuplicate(nums: number[]): boolean {
2+
// Javascript의 Set은 내부적으로 해시테이블을 이용해서, O(n)으로 중복 제거
3+
const uniqueNums = Array.from(new Set(nums).values());
4+
return uniqueNums.length !== nums.length;
5+
};

top-k-frequent-elements/1lsang.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Runtime: 9ms / Memory: 60MB
2+
function topKFrequent(nums: number[], k: number): number[] {
3+
const numFrequency:Record<number, number> = {}; // { n: freq }
4+
5+
for (let i=0; i<nums.length; i++) {
6+
const n = nums[i];
7+
if (numFrequency[n]) numFrequency[n] = numFrequency[n] + 1;
8+
else numFrequency[n] = 1;
9+
}
10+
11+
return Object.entries(numFrequency)
12+
.sort((a, b) => b[1] - a[1])
13+
.slice(0, k)
14+
.map(([_, n])=> n);
15+
};

two-sum/1lsang.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// 1. 가장 간단한 방법 이중 for문 (Runtime: 175ms / Memory: 55.8MB)
2+
// function twoSum(nums: number[], target: number): number[] {
3+
// const length = nums.length;
4+
// for (let i = 0; i < length; i++) {
5+
// for (let j = 0; j < length; j++) {
6+
// if (i === j) continue;
7+
// if (nums[i] + nums[j] === target) return [i, j]
8+
// }
9+
// }
10+
// return [];
11+
// };
12+
13+
// 2. 시간 복잡도 개선 (Runtime: 9ms / Memory: 60.4MB)
14+
function twoSum(nums: number[], target: number): number[] {
15+
const numObj = {};
16+
nums.forEach((num, index) => {numObj[num] ? numObj[num].push(index) : numObj[num]=[index]});
17+
for (let i = 0; i<nums.length; i++) {
18+
const num = target - nums[i];
19+
if (numObj[num]?.length === 1) {
20+
if (i === numObj[num][0]) continue;
21+
return [i, numObj[num][0]];
22+
}
23+
else if (numObj[num]?.length === 2) {
24+
return numObj[num];
25+
}
26+
}
27+
return [];
28+
};

0 commit comments

Comments
 (0)