File tree Expand file tree Collapse file tree 5 files changed +79
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 5 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ # ๋ฆฌ์คํธ ์์ ๋์ผํ ์ซ์๊ฐ 2๊ฐ ์ด์ ์กด์ฌํ๋ฉด true๋ฅผ ๋ฐํํด์ผ ํ๋ ๋ฌธ์
3+ # Set์ผ๋ก ๋ณํ ์ ์ค๋ณต์ด ์ ๊ฑฐ๋๋ฏ๋ก List์ Set์ ํฌ๊ธฐ๋ฅผ ๋น๊ตํด ๋ต์ ๊ตฌํ ์ ์์
4+ def containsDuplicate (self , nums : List [int ]) -> bool :
5+ return len (nums ) != len (set (nums ))
6+
7+ # Time Complexity
8+ # - set(nums) โ O(n)
9+ # - len(nums), len(set(nums)) โ O(1)
10+ # - Total: O(n) (n = number of list elements)
11+
Original file line number Diff line number Diff line change 1+ class Solution {
2+ // ๋ฐฐ์ด์์ ์ธ์ ํ ํญ์ ์ ๊ทผํ ์ ์์ ๋, ์ธ์ ํ์ง ์์ ํญ์ ๋ํด ๊ฐ์ฅ ํฐ ๊ฐ์ ๊ตฌํ๋ ๋ฌธ์
3+ // 1. DP๋ฅผ ์ฌ์ฉํด ๊ฐ ์ง๋ง๋ค ์ ํํ๊ฑฐ๋ ๊ฑด๋๋ฐ๋ ๊ฒฝ์ฐ๋ฅผ ๋์ ๊ณ์ฐ
4+ // 2. ํ์ฌ ์ง์ ํธ ๋, ์ด์ ์ง์ ํธ์ง ์์ ๊ฒฝ์ฐ๋ง ๋ํ ์ ์๊ฒ๋ ๊ณ์ฐ
5+ fun rob (nums : IntArray ): Int {
6+ if (nums.isEmpty()) return 0
7+ var prev1 = 0 // ๋ฐ๋ก ์ด์ ์ง๊น์ง์ ์ต๋ ์ด์ต
8+ var prev2 = 0 // ์ด์ ์ด์ ์ง๊น์ง์ ์ต๋ ์ด์ต
9+
10+ for (num in nums) {
11+ var temp = prev1
12+ prev1 = maxOf(prev2 + num, prev1)
13+ prev2 = temp
14+ }
15+
16+ return prev1
17+ }
18+ }
19+
Original file line number Diff line number Diff line change 1+ class Solution {
2+ // ๋ฐฐ์ด์์ ์ฐ์๋ ์ซ์์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
3+ // 1. ์ค๋ณต์ ์ ๊ฑฐํ๊ณ ์นด์ดํธ
4+ // 2. ์ ๋ ฌํ์ง ์๊ณ ๊ณ์ฐ๋ ๊ฐ๋ฅ
5+ fun longestConsecutive (nums : IntArray ): Int {
6+ if (nums.isEmpty()) return 0
7+
8+ val numSet = nums.toHashSet()
9+ var maxLen = 0
10+
11+ for (num in nums){
12+ if ((num - 1 ) !in numSet){
13+ var currNum = num
14+ var currLen = 1
15+
16+ while ((currNum + 1 ) in numSet){
17+ currNum++
18+ currLen++
19+ }
20+ if (currLen > maxLen) maxLen = currLen
21+ }
22+ }
23+ return maxLen
24+ }
25+ }
26+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ # nums ์์ ๊ฐ์ฅ ๋น๋๊ฐ ๋์ k๊ฐ์ ์์๋ฅผ ์ฐพ๋ ๋ฌธ์
3+ # ๋์
๋๋ฆฌ์ ์ ๋ ฌ์ ์ฌ์ฉํด ํด๊ฒฐ
4+ # ์๊ฐ๋ณต์ก๋: O(n log n), ๊ณต๊ฐ๋ณต์ก๋: O(n)
5+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
6+ freq_map = {}
7+ for num in nums :
8+ freq_map [num ] = freq_map .get (num , 0 ) + 1
9+
10+ sorted_nums = sorted (freq_map .items (), key = lambda x :x [1 ], reverse = True )
11+ return [num for num , _ in sorted_nums [:k ]]
12+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ # 2๊ฐ์ ์๋ฅผ ํฉํด target์ด ๋๋ ๊ฒฝ์ฐ๋ฅผ ์ฐพ๋ ๋ฌธ์
3+ # ์์๊ฐ ๋ณด์ฅ๋๋ python dictionary๋ฅผ ์ฌ์ฉํด์,
4+ # ์์ x์ ๋ํด์ target-x ๊ฐ ๋์
๋๋ฆฌ ๋ด์ ์๋์ง๋ฅผ ์ฐพ๋๋ค.
5+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
6+ dict = {}
7+ for i , num in enumerate (nums ):
8+ remain = target - num
9+ if remain in dict :
10+ return [dict [remain ], i ]
11+ dict [num ] = i
You canโt perform that action at this time.
0 commit comments