diff --git a/contains-duplicate/YOOHYOJEONG.py b/contains-duplicate/YOOHYOJEONG.py new file mode 100644 index 0000000000..0b12f28410 --- /dev/null +++ b/contains-duplicate/YOOHYOJEONG.py @@ -0,0 +1,8 @@ +# https://leetcode.com/problems/contains-duplicate/ + +class Solution(object): + def containsDuplicate(self, nums): + if len(nums) > len(set(nums)): + return True + else: + return False diff --git a/house-robber/YOOHYOJEONG.py b/house-robber/YOOHYOJEONG.py new file mode 100644 index 0000000000..4b0d78b8b6 --- /dev/null +++ b/house-robber/YOOHYOJEONG.py @@ -0,0 +1,15 @@ +# https://leetcode.com/problems/house-robber/ + +class Solution(object): + def rob(self, nums): + + prev = 0 + prev_2 = 0 + + for num in nums: + cur = max(prev, prev_2 + num) + + prev_2 = prev + prev = cur + + return prev diff --git a/longest-consecutive-sequence/YOOHYOJEONG.py b/longest-consecutive-sequence/YOOHYOJEONG.py new file mode 100644 index 0000000000..00c12d651c --- /dev/null +++ b/longest-consecutive-sequence/YOOHYOJEONG.py @@ -0,0 +1,21 @@ +# https://leetcode.com/problems/longest-consecutive-sequence/ + +class Solution(object): + def longestConsecutive(self, nums): + + nums_set = set(nums) + lens = 0 + + for n in nums_set: + + if n-1 not in nums_set: + cur = n + lenth = 1 + + while cur+1 in nums_set: + cur += 1 + lenth += 1 + + lens = max(lens, lenth) + + return lens diff --git a/top-k-frequent-elements/YOOHYOJEONG.py b/top-k-frequent-elements/YOOHYOJEONG.py new file mode 100644 index 0000000000..ec0645eb2c --- /dev/null +++ b/top-k-frequent-elements/YOOHYOJEONG.py @@ -0,0 +1,14 @@ +# https://leetcode.com/problems/top-k-frequent-elements/ + +class Solution(object): + def topKFrequent(self, nums, k): + cnt = {} + for num in nums: + if num in cnt: + cnt[num] += 1 + else: + cnt[num] = 0 + + sorted_cnt = sorted(cnt.items(), key=lambda x: x[1], reverse=True) + + return [item[0] for item in sorted_cnt[:k]] diff --git a/two-sum/YOOHYOJEONG.py b/two-sum/YOOHYOJEONG.py new file mode 100644 index 0000000000..2efc2c35ca --- /dev/null +++ b/two-sum/YOOHYOJEONG.py @@ -0,0 +1,24 @@ +# https://leetcode.com/problems/two-sum/description/ + +# class Solution(object): +# def twoSum(self, nums, target): +# for i in range(len(nums)): +# for j in range(len(nums)): +# if nums[i]+nums[j] == target: +# if i != j: +# return [i, j] +# > 해당 방식 사용 시 시간 복잡도가 O(n²)이라 개선을 해 보고자 아래 솔루션으로 재풀이 진행 + +class Solution(object): + def twoSum(self, nums, target): + seen = {} + + for i, num in enumerate(nums): + diff = target - num + + if diff in seen: + return [seen[diff], i] + + seen[num] = i + +# index를 기억하도록 하면 반복문 한번 O(n), 딕셔너리 조회 평균 O(1)로 전체 O(n)이 됨