Skip to content

Commit e88c1bb

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 7816391 + 895165f commit e88c1bb

File tree

9 files changed

+427
-0
lines changed

9 files changed

+427
-0
lines changed

contains-duplicate/heypaprika.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Big-O 예상 : O(n)
2+
class Solution:
3+
def containsDuplicate(self, nums: List[int]) -> bool:
4+
num_dict = {}
5+
for num in nums:
6+
if num in num_dict:
7+
return True
8+
else:
9+
num_dict[num] = 1
10+
return False
11+

contains-duplicate/ysle0.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package contains_duplicate
2+
3+
import "sort"
4+
5+
/*
6+
1. 문제
7+
8+
주어진 int 배열 nums에 숫자가 중복되는 경우가 한 번이라도 있으면 true, 그렇지 않으면 false 를 리턴
9+
10+
2. 풀이
11+
12+
고유값만 저장하는 set(go 에서는 map)의 성질을 활용하여
13+
nums를 순회하며 set에 값이 있는지 없는지 체크하여
14+
숫자가 중복되는 경우를 체크
15+
16+
3. 분석
17+
- 시간 복잡도: O(N)
18+
nums 탐색: O(N)
19+
배열 nums의 모든 원소를 단 한 번 순회
20+
map 삽입, 탐색: O(1)
21+
map의 내부 구현은 해시 테이블.
22+
O(N)보다 작아 무시됨
23+
- 공간 복잡도: O(N)
24+
최악의 경우라도 사용공간은 nums 의 크기만큼 + nums의 모든 원소를 포함한 map
25+
*/
26+
func containsDuplicate(nums []int) bool {
27+
seen := map[int]int{}
28+
29+
for _, n := range nums {
30+
if _, ok := seen[n]; ok {
31+
return true
32+
}
33+
34+
seen[n] = 1
35+
}
36+
37+
return false
38+
}
39+
40+
func containsDuplicate_SortedApproach(nums []int) bool {
41+
// early exit for small slices
42+
if len(nums) < 2 {
43+
return false
44+
}
45+
46+
// sort in ascending order and check adjacent elements
47+
sort.Ints(nums)
48+
for i := 1; i < len(nums); i++ {
49+
if nums[i] == nums[i-1] {
50+
return true
51+
}
52+
}
53+
54+
return false
55+
}

house-robber/heypaprika.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Big-O 예상 : O(n)
2+
class Solution:
3+
def rob(self, nums: List[int]) -> int:
4+
a = [0] * len(nums)
5+
6+
if len(nums) == 1:
7+
return nums[0]
8+
elif len(nums) == 2:
9+
return max(nums[0], nums[1])
10+
11+
a[0] = nums[0]
12+
a[1] = nums[1]
13+
a[2] = max(a[0] + nums[2], a[1])
14+
15+
for i in range(3, len(nums)):
16+
a[i] = max(a[i-3], a[i-2]) + nums[i]
17+
18+
return max(a)
19+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Big-O 예상 : O(nlog(n))
2+
class Solution:
3+
def longestConsecutive(self, nums: List[int]) -> int:
4+
nums = sorted(list(set(nums)))
5+
if len(nums) == 0:
6+
return 0
7+
elif len(nums) == 1:
8+
return 1
9+
cur_long = 1
10+
longest = 1
11+
for i, num in enumerate(nums):
12+
if i == 0:
13+
continue
14+
else:
15+
if nums[i-1] + 1 == nums[i]:
16+
cur_long += 1
17+
if longest < cur_long:
18+
longest = cur_long
19+
else:
20+
cur_long = 1
21+
return longest
22+
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package longest_consecutive_sequence
2+
3+
import "slices"
4+
5+
/*
6+
1. 문제
7+
주어진 int 배열 nums에서 찾을 수 있는 가장 긴 연속된 원소의 길이 구하기
8+
9+
2. 풀이
10+
모든 수의 중복을 제거하고, 오름차순으로 정렬하여 연속된 원소의 부분을 찾기 위해서
11+
배열을 순회하여 인덱스 고정~전진하며 다음 원소가 연속된 원소인지 체크를 반복
12+
13+
3. 분석
14+
15+
- 시간 복잡도: O(N logN)
16+
배열 정렬 O(N logN)
17+
중복된 원소를 제거해주는 slices.Compact(nums): O(N)
18+
2중 포문은 for 문 순회 index 를 같이 쓰므로 O(N)
19+
20+
- 공간 복잡도: O(N)
21+
*/
22+
func longestConsecutive(nums []int) int {
23+
if len(nums) == 0 {
24+
return 0
25+
}
26+
27+
if len(nums) == 1 {
28+
return 1
29+
}
30+
31+
slices.Sort(nums)
32+
nums = slices.Compact(nums)
33+
// 중복을 제거하고 나서도 1개면 최장연속수는 1
34+
if len(nums) == 1 {
35+
return 1
36+
}
37+
38+
cons := map[int]int{}
39+
cursor := 0
40+
for cursor < len(nums)-1 {
41+
cons[cursor] = 1
42+
wasConsecutive := false
43+
44+
// cursor 는 고정하고, innerCursor 를 돌림
45+
innerCursor := cursor
46+
for innerCursor+1 < len(nums) &&
47+
nums[innerCursor]+1 == nums[innerCursor+1] {
48+
49+
cons[cursor]++
50+
innerCursor++
51+
wasConsecutive = true
52+
}
53+
54+
if wasConsecutive {
55+
cursor = innerCursor
56+
}
57+
cursor++
58+
}
59+
60+
//tmp := make([]int, 0, len(cons))
61+
tmp := make([]int, 0, len(cons))
62+
for _, v := range cons {
63+
tmp = append(tmp, v)
64+
}
65+
66+
slices.SortFunc(
67+
tmp,
68+
func(a, b int) int {
69+
return b - a
70+
})
71+
return tmp[0]
72+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Big-O 예상 : O(nlog(n))
2+
import heapq
3+
class Solution:
4+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
5+
6+
num_dict = {}
7+
for num in nums:
8+
num_dict[num] = num_dict.get(num, 0) + 1
9+
heap = []
10+
for k_, v in num_dict.items():
11+
heapq.heappush(heap, [-v, k_])
12+
ans = []
13+
for i in range(k):
14+
ans.append(heapq.heappop(heap)[1])
15+
return ans
16+

top-k-frequent-elements/ysle0.go

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
package top_k_frequent_elements
2+
3+
//package main
4+
5+
import (
6+
"container/heap"
7+
"slices"
8+
)
9+
10+
/*
11+
1. 문제
12+
nums 에서 가장 많이 나온 숫자들 k 개를 반환.
13+
14+
2. 풀이
15+
map 에 빈도를 기록하여 내림차순 정렬한 후 k개 뽑기
16+
17+
3. 분석
18+
19+
- 시간 복잡도: O(N + M logM) --> O(N logN)
20+
빈도맵핑을 위한 nums 순회: O(N)
21+
오름차순정렬: O(M logM)
22+
23+
- 공간 복잡도: O(N)
24+
주어진 배열 nums: O(N)
25+
빈도맵핑용 map: O(N)
26+
*/
27+
type Kvp struct {
28+
k int
29+
v int
30+
}
31+
32+
func topKFrequent(nums []int, k int) []int {
33+
freq := map[int]int{}
34+
35+
// 빈도를 기록
36+
for _, n := range nums {
37+
if _, ok := freq[n]; !ok {
38+
freq[n] = 1
39+
} else {
40+
freq[n]++
41+
}
42+
}
43+
44+
// map->array
45+
tmp := make([]Kvp, 0, len(freq))
46+
for key, v := range freq {
47+
tmp = append(tmp, Kvp{key, v})
48+
}
49+
50+
// 내림차순 정렬 (time O(M logM)
51+
slices.SortFunc(tmp, func(a, b Kvp) int { return b.v - a.v })
52+
53+
// []int 로 변환
54+
res := make([]int, 0, len(tmp))
55+
for _, kvp := range tmp {
56+
res = append(res, kvp.k)
57+
}
58+
59+
// k 개 뽑기
60+
return res[:k]
61+
}
62+
63+
func topKElements_HeapBasedApproach(nums []int, k int) []int {
64+
freq := map[int]int{}
65+
for _, n := range nums {
66+
freq[n]++
67+
}
68+
69+
h := &IntHeap{}
70+
heap.Init(h)
71+
72+
for k, v := range freq {
73+
heap.Push(h, Kvp{k, v})
74+
if h.Len() > k {
75+
heap.Pop(h)
76+
}
77+
}
78+
79+
res := make([]int, k)
80+
for i := k - 1; i >= 0; i-- {
81+
res[i] = heap.Pop(h).(Kvp).k
82+
}
83+
84+
return res
85+
}
86+
87+
type IntHeap []Kvp
88+
89+
func (h *IntHeap) Len() int { return len(*h) }
90+
func (h *IntHeap) Less(i, j int) bool { return (*h)[i].v < (*h)[j].v }
91+
func (h *IntHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] }
92+
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(Kvp)) }
93+
func (h *IntHeap) Pop() interface{} {
94+
old := *h
95+
n := len(old)
96+
x := old[n-1]
97+
*h = old[0 : n-1]
98+
return x
99+
}
100+
101+
func topKFrequentElements_BucketSort(nums []int, k int) []int {
102+
freq := map[int]int{}
103+
for _, n := range nums {
104+
freq[n]++
105+
}
106+
107+
buc := make([][]int, len(nums)+1)
108+
for k, v := range freq {
109+
buc[v] = append(buc[v], k)
110+
}
111+
112+
res := []int{}
113+
for i := len(buc) - 1; i >= 0 && len(res) < k; i-- {
114+
res = append(res, buc[i]...)
115+
}
116+
117+
return res[:k]
118+
}
119+
120+
//
121+
//func main() {
122+
// r1 := topKFrequent([]int{1, 1, 1, 2, 2, 3}, 2)
123+
// fmt.Println(r1)
124+
//
125+
// r2 := topKFrequent([]int{1}, 1)
126+
// fmt.Println(r2)
127+
//}

valid-palindrome/heypaprika.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Big-O 예상 : O(n)
2+
class Solution:
3+
def isPalindrome(self, s: str) -> bool:
4+
s = "".join(s.lower().split(" "))
5+
new_s = ""
6+
for item in s:
7+
if (ord("a") <= ord(item) <= ord("z")) or (ord("0") <= ord(item) <= ord("9")):
8+
new_s += item
9+
output = True
10+
new_s_2 = new_s[::-1]
11+
return new_s_2 == new_s
12+
return output
13+

0 commit comments

Comments
 (0)