File tree Expand file tree Collapse file tree 14 files changed +551
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 14 files changed +551
-0
lines changed Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Source: https://leetcode.com/problems/contains-duplicate/
3
+ * 풀이방법: Set을 이용하여 중복된 값이 있는지 확인
4
+ * 시간복잡도: O(n)
5
+ * 공간복잡도: O(n)
6
+ *
7
+ * 생각나는 풀이방법
8
+ * 1. 단순하게 sorted를 이용하여 이전값과 비교하여 중복된 값이 있는지 확인
9
+ * 2. 정렬하지 않고 nums의 길이만큼의 배열을 만들어서 중복된 값이 있는지 저장하면서 확인
10
+ */
11
+ function containsDuplicate ( nums : number [ ] ) : boolean {
12
+ // 중복된 값이 없는 자료구조 Set 활용
13
+ const set = new Set < number > ( nums ) ;
14
+ // Set의 size와 nums의 length를 비교하여 중복된 값이 있는지 확인
15
+ return set . size !== nums . length ;
16
+ }
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Source: https://leetcode.com/problems/house-robber/
3
+ * 풀이방법: DP를 이용하여 집을 털 때 최대값을 구함
4
+ * 시간복잡도: O(n)
5
+ * 공간복잡도: O(n)
6
+ *
7
+ * 생각나는 풀이방법
8
+ */
9
+ function rob ( nums : number [ ] ) : number {
10
+ if ( nums . length === 0 ) return 0 ;
11
+ if ( nums . length === 1 ) return nums [ 0 ] ;
12
+ if ( nums . length === 2 ) return Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
13
+
14
+ let prev = nums [ 0 ] ;
15
+ let maxResult = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
16
+ let current = 0 ;
17
+
18
+ // 남은 집을 순회하면서 최대값을 구함
19
+ for ( let i = 2 ; i < nums . length ; i ++ ) {
20
+ current = Math . max ( maxResult , prev + nums [ i ] ) ;
21
+ prev = maxResult ;
22
+ maxResult = current ;
23
+ }
24
+ return maxResult ;
25
+ }
Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Source: https://leetcode.com/problems/longest-consecutive-sequence/
3
+ * 풀이방법: 정렬 후 순회를 통해 연속된 값이 있는지 확인
4
+ * 시간복잡도: O(nlogn)
5
+ * 공간복잡도: O(1)
6
+ *
7
+ * 생각나는 풀이방법
8
+ */
9
+
10
+ function longestConsecutive ( nums : number [ ] ) : number {
11
+ if ( nums . length === 0 ) return 0 ;
12
+ const sorted = nums . sort ( ( a , b ) => a - b ) ;
13
+ let prev = sorted [ 0 ] ;
14
+ let result = 1 ;
15
+ let candiResult = 1 ;
16
+
17
+ for ( let current of sorted ) {
18
+ if ( prev === current ) continue ;
19
+ if ( current === prev + 1 ) {
20
+ candiResult += 1 ;
21
+ } else {
22
+ if ( candiResult > result ) {
23
+ result = candiResult ;
24
+ }
25
+ candiResult = 1 ;
26
+ }
27
+ prev = current ;
28
+ }
29
+
30
+ if ( candiResult > result ) result = candiResult ;
31
+ return result ;
32
+ }
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Source: https://leetcode.com/problems/top-k-frequent-elements/
3
+ * 풀이방법: 순회를 통해 빈도수를 저장, Object.entries를 통해 정렬하여 k개까지 반환
4
+ * 시간복잡도: O(nlogn)
5
+ * 공간복잡도: O(n)
6
+ *
7
+ * 생각나는 풀이방법
8
+ */
9
+ function topKFrequent ( nums : number [ ] , k : number ) : number [ ] {
10
+ const KFrequentObject = new Object ( ) ;
11
+ const result = new Array ( ) ;
12
+ for ( let num of nums ) {
13
+ if ( ! Object . hasOwn ( KFrequentObject , num ) ) KFrequentObject [ num ] = 0 ;
14
+ KFrequentObject [ num ] ++ ;
15
+ }
16
+ // Object.entries를 통해 key, value를 배열로 반환 (포인트)
17
+ let sorted = Object . entries ( KFrequentObject ) . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] ) ;
18
+ for ( let node of sorted ) {
19
+ result . push ( parseInt ( node [ 0 ] ) ) ;
20
+ }
21
+ return result . slice ( 0 , k ) ;
22
+ }
You can’t perform that action at this time.
0 commit comments