Skip to content

Commit 9cc99d4

Browse files
authored
Merge pull request #460 from whewchews/main
[pepper] Week 5 Solutions
2 parents f1b408d + 6fdca7f commit 9cc99d4

File tree

5 files changed

+234
-0
lines changed

5 files changed

+234
-0
lines changed

3sum/whewchews.ts

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function threeSum(nums: number[]): number[][] {
2+
let result: [number, number, number][] = [];
3+
const TARGET = 0;
4+
// TC: O(NlogN)
5+
nums.sort((a, b) => a - b);
6+
7+
for (let i = 0; i < nums.length - 2; i++) {
8+
if (i > 0 && nums[i] === nums[i - 1]) continue;
9+
10+
let left = i + 1;
11+
let right = nums.length - 1;
12+
13+
while (left < right) {
14+
let sum = nums[i] + nums[left] + nums[right];
15+
16+
if (sum === TARGET) {
17+
result.push([nums[i], nums[left], nums[right]]);
18+
while (nums[left] === nums[left + 1]) left++;
19+
while (nums[right] === nums[right - 1]) right--;
20+
left++;
21+
right--;
22+
} else if (sum < TARGET) {
23+
left++;
24+
} else {
25+
right--;
26+
}
27+
}
28+
}
29+
30+
return result;
31+
}
32+
// TC: O(n^2)
33+
// SC: O(n)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* 아이디어
3+
* 수익을 얻기 위해서는 index보다 뒤에 오는 값 중에 현재 값보다 큰 값이 있어야 한다
4+
* 차이가 가장 큰 두 값을 찾으면 되는데, 그 값의 순서가 작은값 다음 큰 값 순이어야 한다
5+
* 가격의 차이를 어떻게 구할 수 있을까?
6+
* for문을 두번 돌면서 값의 차이를 저장해둔다.(순서가 일치해야함)
7+
* 값의 차이 중 가장 큰 값을 리턴한다.
8+
* 리턴할 값이 없으면 0을 리턴한다.
9+
* ====> 이 방법으로 풀었더니 타임초과가 나왔다.
10+
* 어떻게 시간복잡도를 줄일 수 있을까?
11+
* for문을 두번돌면 O(n^2)이 드니 for문을 한번만 돌게 하면 좋을 것 같다.
12+
* for문을 돌면서 가장 작은 구매가, 최대 이익 두가지 변수를 업데이트 하자
13+
* ===> 연습삼아 투포인터로도 풀어보자
14+
*/
15+
16+
function maxProfit1(prices: number[]): number {
17+
let profit = 0;
18+
19+
for (let i = 0; i <= prices.length - 2; i++) {
20+
const x = prices[i];
21+
for (let j = i + 1; j <= prices.length - 1; j++) {
22+
const y = prices[j];
23+
const diff = y - x;
24+
if (x < y && profit < diff) {
25+
profit = diff;
26+
}
27+
}
28+
}
29+
30+
return profit;
31+
}
32+
// TC: O(n^2)
33+
// SC: O(1)
34+
35+
function maxProfit2(prices: number[]): number {
36+
let buyPrice = prices[0];
37+
let profit = 0;
38+
39+
for (let i = 0; i <= prices.length - 1; i++) {
40+
const todayPrice = prices[i];
41+
const diff = todayPrice - buyPrice;
42+
43+
if (todayPrice <= buyPrice) {
44+
buyPrice = todayPrice;
45+
} else {
46+
if (profit < diff) {
47+
profit = todayPrice - buyPrice;
48+
}
49+
}
50+
}
51+
52+
return profit;
53+
}
54+
// TC: O(n)
55+
// SC: O(1)
56+
57+
function maxProfit3(prices: number[]): number {
58+
let left = 0;
59+
let right = 1;
60+
let maxProfit = 0;
61+
62+
while (right <= prices.length - 1) {
63+
if (prices[left] > prices[right]) {
64+
left = right;
65+
} else {
66+
const profit = prices[right] - prices[left];
67+
maxProfit = Math.max(profit, maxProfit);
68+
}
69+
70+
right++;
71+
}
72+
73+
return maxProfit;
74+
}
75+
// TC: O(n)
76+
// SC: O(1)

group-anagrams/whewchews.ts

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* 조건
3+
* 문자열은 영어 소문자
4+
* 서로 anagram이 되는 쌍을 배열로 묶어서 리턴
5+
* 자기 자신은 anagram 혼자서 가능함
6+
* return 하는 배열 순서는 관계없음
7+
8+
* 아이디어
9+
* strs를 돌면서 str에 어떤 알파벳이 몇개씩 있는지를 계산한다
10+
* 알파벳 개수가 같은 문자열끼리 몹는다
11+
*/
12+
function groupAnagrams(strs: string[]): string[][] {
13+
const anagramMap = new Map<string, string[]>();
14+
15+
for (const str of strs) {
16+
const sortedStr = generateAnagramKey2(str);
17+
if (!anagramMap.has(sortedStr)) {
18+
anagramMap.set(sortedStr, []);
19+
}
20+
21+
anagramMap.get(sortedStr)!.push(str);
22+
}
23+
24+
return Array.from(anagramMap.values());
25+
}
26+
// TC: O(N * M)
27+
// SC: O(N * M)
28+
29+
function generateAnagramKey1(str: string): string {
30+
return str.split("").sort().join("");
31+
}
32+
// TC: O(NlogN)
33+
// SC: O(N)
34+
35+
function generateAnagramKey2(str: string): string {
36+
let count = new Array(26).fill(0);
37+
38+
for (let c of str) {
39+
count[c.charCodeAt(0) - "a".charCodeAt(0)]++;
40+
}
41+
42+
return count.join("-");
43+
}
44+
// TC: O(N)
45+
// SC: O(1)
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* 아이디어
3+
* 삽입된 전체 word를 저장해둔다. => wordSet
4+
* 삽입된 단어의 1글자 ~ 단어길이 글자 만큼을 전부 각각 prefix로 저장해둔다. => prefixSet
5+
* 중복처리를 위해 Set을 사용한다.
6+
*/
7+
class Trie {
8+
wordSet: Set<string>;
9+
prefixSet: Set<string>;
10+
11+
constructor() {
12+
this.wordSet = new Set();
13+
this.prefixSet = new Set();
14+
}
15+
16+
// TC: O(n) // n = word.length
17+
// SC: O(n)
18+
insert(word: string): void {
19+
let result = "";
20+
for (let i = 0; i < word.length; i++) {
21+
result += word[i];
22+
this.prefixSet.add(result);
23+
}
24+
this.wordSet.add(word);
25+
}
26+
27+
// TC: O(1)
28+
// SC: O(1)
29+
search(word: string): boolean {
30+
return this.wordSet.has(word);
31+
}
32+
33+
// TC: O(1)
34+
// SC: O(1)
35+
startsWith(prefix: string): boolean {
36+
return this.prefixSet.has(prefix);
37+
}
38+
}
39+
40+
/**
41+
* Your Trie object will be instantiated and called as such:
42+
* var obj = new Trie()
43+
* obj.insert(word)
44+
* var param_2 = obj.search(word)
45+
* var param_3 = obj.startsWith(prefix)
46+
*/

word-break/whewchews.ts

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* 조건
3+
* 영어소문자로만 구성되어있음
4+
* wordDict안에 있는 문자를 가지고 s를 만들 수 있으면 true return
5+
6+
* 아이디어
7+
* wordDict안에 있는 단어들 중 s의 prefix 단어를 찾는다.
8+
* prefix가 되는 단어를 뺀, 나머지 뒤의 문자열이 wordDict안에 있는 단어로 시작되는지 찾는다.
9+
* 이 과정을 반복해서, s의 길이가 0이 되면 true를 리턴한다.
10+
* wordDict안에 있는 단어를 다 조회해도 s가 남아있다면 false를 리턴한다.
11+
*/
12+
13+
function wordBreak(s: string, wordDict: string[]): boolean {
14+
const memo: Record<string, boolean> = {};
15+
return isBreak(s, wordDict, memo);
16+
}
17+
18+
function isBreak(s: string, wordDict: string[], memo: Record<string, boolean>) {
19+
if (s.length === 0) return true;
20+
if (s in memo) return memo[s];
21+
for (const word of wordDict) {
22+
const length = word.length;
23+
if (s.startsWith(word) && isBreak(s.slice(length), wordDict, memo)) {
24+
memo[s] = true;
25+
return true;
26+
}
27+
}
28+
29+
memo[s] = false;
30+
return false;
31+
}
32+
// TC: O(s*w)
33+
// SC: O(s)
34+
// s: s.length, w: wordDict.length

0 commit comments

Comments
 (0)