Skip to content

Commit ad4791d

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents f0db96a + ced8e07 commit ad4791d

File tree

19 files changed

+553
-0
lines changed

19 files changed

+553
-0
lines changed

contains-duplicate/Chaedie.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
3+
'''
4+
풀이:
5+
중복된 요소가 있는지 찾는 문제입니다.
6+
7+
hash set 으로 중복을 제거하고
8+
기존 nums 의 길이와 중복 제거된 nums_set 의 길이가 같은지 return 했습니다.
9+
10+
시간 복잡도:
11+
O(n) - has set 을 만드는 시간
12+
13+
공간 복잡도:
14+
O(n) - n개의 요소를 set에 담기 때문
15+
'''
16+
17+
18+
class Solution:
19+
def containsDuplicate(self, nums: List[int]) -> bool:
20+
nums_set = set(nums)
21+
return len(nums_set) != len(nums)

contains-duplicate/limlimjo.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
var containsDuplicate = function(nums) {
6+
7+
// 첫 번째 방법: filter + indexOf 사용 => indexOf(),filter() 각각 시간복잡도 O(n) 두 개가 중첩이므로 시간복잡도 O(n^2)
8+
// Runtime: Time Limit Exceeded 발생
9+
const method1 = function() {
10+
const filterNums = nums.filter((item,index) => nums.indexOf(item) !== index);
11+
return filterNums.length > 0;
12+
}
13+
14+
// 두 번째 방법: Set 사용 => nums 배열을 set으로 변환할 때 한번씩 확인하면 되므로 시간복잡도 O(n)
15+
// Runtime: 14ms
16+
const method2 = function() {
17+
const setNums = new Set(nums);
18+
return setNums.size !== nums.length;
19+
}
20+
21+
// 위 두 가지 방법 중 Set을 사용하는 것이 성능상 훨씬 나음
22+
return method2();
23+
};

contains-duplicate/pmjuu.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
class Solution:
2+
def containsDuplicate(self, nums: List[int]) -> bool:
3+
return len(nums) != len(set(nums))

contains-duplicate/taewanseoul.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* 217. Contains Duplicate
3+
* Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
4+
* https://leetcode.com/problems/contains-duplicate/description/
5+
*/
6+
function containsDuplicate(nums: number[]): boolean {
7+
const set = new Set<number>();
8+
9+
for (let i = 0; i < nums.length; i++) {
10+
if (set.has(nums[i])) {
11+
return true;
12+
}
13+
set.add(nums[i]);
14+
}
15+
16+
return false;
17+
}
18+
19+
// TC: O(n)
20+
// https://262.ecma-international.org/15.0/index.html#sec-get-set.prototype.size
21+
// Set objects must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structure used in this specification is only intended to describe the required observable semantics of Set objects. It is not intended to be a viable implementation model.

house-robber/Chaedie.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
'''
2+
Solution:
3+
스스로 풀지 못해 학습만 진행했습니다.
4+
다음 기회에 다시 풀어보도록 하겠습니다.
5+
'''
6+
class Solution:
7+
def rob(self, nums: List[int]) -> int:
8+
prev, curr = 0, 0
9+
for num in nums:
10+
prev, curr = curr, max(num + prev, curr)
11+
12+
return curr
13+
14+
15+
# class Solution:
16+
# '''
17+
# 4. 달레의 코드 풀이 - DP, prev, curr
18+
# O(n) time
19+
# O(1) space
20+
# '''
21+
22+
# # 달레의 코드 풀이 - DP, prev, cur
23+
24+
# def rob(self, nums: List[int]) -> int:
25+
# prev, curr = 0, 0
26+
# for num in nums:
27+
# prev, curr = curr, max(num + prev, curr)
28+
29+
# return curr
30+
31+
# '''
32+
# 3. 달레의 코드 풀이 - DP
33+
# [1,2,3,1]
34+
# [1, 2, 3, 1]
35+
# DP:[0, 1, 2, 4, 4]
36+
# MAX(1 + DP[2], DP[1]) = MAX(1 + 2, 4) = 4
37+
# '''
38+
# # 달레의 코드 풀이 - DP
39+
# # def rob(self, nums: List[int]) -> int:
40+
# # dp = [0] * (len(nums) + 1)
41+
# # dp[1] = nums[0]
42+
# # for n in range(2,len(nums) + 1):
43+
# # dp[n] = max(nums[n - 1] + dp[n - 2], dp[n - 1])
44+
# # return dp[-1]
45+
# '''
46+
# 2. 달레의 코드 풀이 - 재귀, 메모이제이션
47+
# time: O(n)
48+
# space: O(n)
49+
# '''
50+
# # 달레의 코드 풀이 - 재귀, 메모이제이션
51+
# # def rob(self, nums: List[int]) -> int:
52+
# # memo = {}
53+
54+
# # def dfs(start):
55+
# # if start in memo:
56+
# # return memo[start]
57+
# # if not start < len(nums):
58+
# # memo[start] = 0
59+
# # else:
60+
# # memo[start] = max(nums[start] + dfs(start + 2), dfs(start + 1))
61+
# # return memo[start]
62+
# # return dfs(0)
63+
# '''
64+
# 1. 달레의 코드 풀이 - 재귀
65+
# time: O(2^n)
66+
# space: O(n)
67+
68+
# F([1,2,3,1]) => MAX(1 + F([3,1], f([2,3,1])))
69+
# F([3,1]) => MAX(3 + F([]), F([1]))
70+
# F([]) => 0
71+
# F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1
72+
# F([]) => 0
73+
# F([]) => 0
74+
# F([2,3,1]) => MAX(2 + F([1]), F([3,1]))
75+
# F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1
76+
# F([]) => 0
77+
# F([]) => 0
78+
# F([3,1]) => MAX(3 + F([]), F([1]))
79+
# F([]) => 0
80+
# F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1
81+
# F([]) => 0
82+
# F([]) => 0
83+
# 재귀가 불필요하게 반복되고 있다.
84+
# 메모이제이션으로 기억해두면 반복은 스킵할 수 있다.
85+
# '''
86+
# # 달레의 코드 풀이 - 재귀
87+
# # def rob(self, nums: List[int]) -> int:
88+
89+
# # def dfs(start):
90+
# # if not start < len(nums):
91+
# # return 0
92+
# # return max(nums[start] + dfs(start + 2), dfs(start + 1))
93+
# # return dfs(0)
94+
95+
# # neetcode 풀이 - DP, 이해안됨...
96+
# # def rob(self, nums: List[int]) -> int:
97+
# # rob1, rob2 = 0, 0
98+
# # # [rob1, rob2, n, n+1, ...]
99+
# # for n in nums:
100+
# # temp = max(n + rob1, rob2)
101+
# # rob1 = rob2
102+
# # rob2 = temp
103+
# # return rob2

house-robber/limlimjo.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var rob = function(nums) {
6+
// 1. nums 배열 0일 때와 1일 때
7+
if (nums.length === 0) return 0;
8+
if (nums.length === 1) return nums[0];
9+
10+
// 2. i=1일 때
11+
nums[1] = Math.max(nums[0], nums[1]);
12+
13+
// 3. i=2일 때부터 for문 순회
14+
for (let i=2; i<nums.length; i++) {
15+
nums[i] = Math.max(nums[i-2] + nums[i], nums[i-1])
16+
}
17+
return nums[nums.length-1];
18+
};
19+
20+
// 시간복잡도와 공간복잡도
21+
// 시간복잡도: 배열의 길이 n 만큼 for문 순회하므로 -> O(n)
22+
// 공간복잡도: nums 배열 그대로 수정하여 계산 -> O(1)

house-robber/pmjuu.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from typing import List
2+
3+
class Solution:
4+
def rob(self, nums: List[int]) -> int:
5+
if len(nums) == 1:
6+
return nums[0]
7+
8+
# prev1: 이전 집까지의 최대 이익
9+
# prev2: 전전 집까지의 최대 이익
10+
prev1, prev2 = 0, 0
11+
for num in nums:
12+
temp = prev1
13+
prev1 = max(prev2 + num, prev1) # 현재 집을 털었을 때와 안 털었을 때 중 더 큰 이익 선택
14+
prev2 = temp
15+
16+
return prev1
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Solution:
3+
0. i will use prev, cur pointers in for loop,
4+
so i have to get rid of edge case when len of nums is at most 1
5+
1. use hash set for remove duplicate elements
6+
2. sort list
7+
3. iterate sorted_nums and use two pointers (prev, cur)
8+
compare prev and cur and count if the difference is 1
9+
4. use max method, memorize maxCount
10+
5. return maxCount
11+
12+
Time Complexity:
13+
1. remove duplicate by hash set -> O(n)
14+
2. sort the list -> O(n log n)
15+
3. iterate sorted_nums -> O(n)
16+
17+
so time complexity of this solution will be O(n log n)
18+
19+
Space Complexity:
20+
1. set() -> O(n)
21+
2. sorted_nums -> O(n)
22+
3. count , maxCount -> O(1)
23+
24+
space complexity of this solution will be O(n)
25+
"""
26+
27+
28+
class Solution:
29+
def longestConsecutive(self, nums: List[int]) -> int:
30+
if len(nums) <= 1:
31+
return len(nums)
32+
33+
sorted_nums = sorted(list(set(nums)))
34+
35+
count = 1
36+
maxCount = 1
37+
for i in range(1, len(sorted_nums)):
38+
prev = sorted_nums[i - 1]
39+
cur = sorted_nums[i]
40+
if prev + 1 == cur:
41+
count += 1
42+
maxCount = max(count, maxCount)
43+
else:
44+
count = 1
45+
46+
return maxCount
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function(nums) {
6+
// 첫 번째 정렬을 한다.
7+
if (nums.length === 0) {
8+
return 0;
9+
}
10+
11+
nums.sort((a, b) => a - b); // 오름차순으로 정렬
12+
console.log(nums);
13+
14+
// 두 번째 숫자가 1씩 계속해서 증가하는 구간을 찾는다.
15+
let longest = 0;
16+
let length = 1;
17+
18+
for (let i=0; i<nums.length-1; i++) {
19+
if (nums[i] === nums[i+1]) {
20+
continue;
21+
}
22+
// 연속해서 1씩 증가하는 구간 찾기
23+
if (nums[i+1] - nums[i] === 1) {
24+
length += 1;
25+
} else {
26+
longest = Math.max(longest, length);
27+
length = 1;
28+
}
29+
}
30+
return Math.max(longest, length);
31+
};
32+
33+
// 시간복잡도와 공간복잡도
34+
// 시간복잡도: 정렬 사용(O(nlogn)) + for문으로 배열 탐색(O(n)) = O(nlogn)
35+
// 공간복잡도: O(1)

longest-consecutive-sequence/pmjuu.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import List
2+
3+
class Solution:
4+
def longestConsecutive(self, nums: List[int]) -> int:
5+
# Convert to set for O(1) lookups
6+
num_set = set(nums)
7+
longest_length = 0
8+
9+
for num in num_set:
10+
# Only start counting if num is the start of a sequence
11+
if num - 1 not in num_set:
12+
current_num = num
13+
current_length = 1
14+
15+
# Count the length of the sequence
16+
while current_num + 1 in num_set:
17+
current_num += 1
18+
current_length += 1
19+
20+
longest_length = max(longest_length, current_length)
21+
22+
return longest_length
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 128. Longest Consecutive Sequence
3+
* Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
4+
*
5+
* You must write an algorithm that runs in O(n) time.
6+
* https://leetcode.com/problems/longest-consecutive-sequence/description/
7+
*/
8+
function longestConsecutive(nums: number[]): number {
9+
const set = new Set(nums);
10+
const sorted = [...set].sort((a, b) => a - b);
11+
12+
if (sorted.length === 0) {
13+
return 0;
14+
}
15+
16+
let longestSequence = 1;
17+
let currentSequence = 1;
18+
for (let i = 0; i - 1 < sorted.length; i++) {
19+
if (Math.abs(sorted[i + 1] - sorted[i]) === 1) {
20+
currentSequence++;
21+
} else {
22+
if (currentSequence > longestSequence) {
23+
longestSequence = currentSequence;
24+
}
25+
currentSequence = 1;
26+
}
27+
}
28+
29+
return longestSequence;
30+
}
31+
32+
// O(n) time
33+
// O(n) space

top-k-frequent-elements/Chaedie.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Solution:
3+
1. make a dictionary of (index, Frequency)
4+
2. sort the items of dictionary by Frequency
5+
3. return list of Top k Frequent Elements
6+
7+
Time Complexity:
8+
1. iterate nums for counting -> O(n)
9+
2. sort -> O(n log n)
10+
3. iterate list for making return value -> O(n)
11+
12+
So Time complexity of this solution is O(n log n)
13+
14+
Space Complexity:
15+
1. dictionary for counting frequency of nums -> O(n)
16+
2. Timsort's space overhead -> O(n)
17+
3. sorted List -> O(n)
18+
19+
Space complexity of this solution is O(n)
20+
"""
21+
22+
23+
class Solution:
24+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
25+
counts = defaultdict(int)
26+
for num in nums:
27+
counts[num] += 1
28+
29+
result = sorted(counts.items(), key=lambda x: x[1], reverse=True)
30+
return list(map(lambda x: x[0], result[:k]))

0 commit comments

Comments
 (0)