Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EGON] Week 01 Solutions #322

Merged
merged 4 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions contains-duplicate/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from unittest import TestCase, main
from typing import List
from collections import Counter


class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return self.solve_3(nums=nums)

"""
Runtime: 412 ms (Beats 75.17%)
Analyze Complexity: O(n)
Memory: 31.92 MB (Beats 45.93%)
"""
def solve_1(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))

"""
Runtime: 423 ms (Beats 39.66%)
Analyze Complexity: O(n)
Memory: 34.54 MB (Beats 14.97%)
"""
def solve_2(self, nums: List[int]) -> bool:
counter = {}
for num in nums:
if num in counter:
return True
else:
counter[num] = True
else:
return False

"""
Runtime: 441 ms (Beats 16.59%)
Analyze Complexity: O(n)
Memory: 34.57 MB (Beats 14.97%)
"""
def solve_3(self, nums: List[int]) -> bool:
return Counter(nums).most_common(1)[0][1] > 1


class _LeetCodeTCs(TestCase):
def test_1(self):
nums = [1, 2, 3, 1]
output = True
self.assertEqual(Solution.containsDuplicate(Solution(), nums=nums), output)

def test_2(self):
nums = [1, 2, 3, 4]
output = False
self.assertEqual(Solution.containsDuplicate(Solution(), nums=nums), output)

def test_3(self):
nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
output = True
self.assertEqual(Solution.containsDuplicate(Solution(), nums=nums), output)


if __name__ == '__main__':
main()
34 changes: 34 additions & 0 deletions contains-duplicate/EGON.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import Foundation

class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
return solve_2(nums)
}

/*
Runtime: 246 ms (Beats 68.44%)
Analyze Complexity: O(n)
Memory: 19.94 MB (Beats 76.01%)
*/
func solve_1(_ nums: [Int]) -> Bool {
return nums.count != Set(nums).count
}

/*
Runtime: 240 ms (Beats 90.56%)
Analyze Complexity: O(n)
Memory: 22.56 MB (Beats 33.43%)
*/
func solve_2(_ nums: [Int]) -> Bool {
var counter: [Int: Bool] = [:]
for num in nums {
if counter[num] != nil {
return true
} else {
counter[num] = true
}
}

return false
}
}
111 changes: 111 additions & 0 deletions kth-smallest-element-in-a-bst/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
from typing import Optional, List
from unittest import TestCase, main
from heapq import heappush, heappop


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
return self.solve_2(root, k)

"""
Runtime: 50 ms (Beats 25.03%)
Analyze Complexity: O(n * log n), 순회에 n, heap push에 log n
Memory: 19.55 MB (Beats 15.91%)
"""
def solve_1(self, root: Optional[TreeNode], k: int) -> int:
visited = []
stack = [root]
while stack:
curr_node = stack.pop()
heappush(visited, curr_node.val)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다양한 풀이로 하셔서 좋네요 :) 요부분 조금 궁금한게 있는데, bst의 heappush의 Time complexity가 제 기억엔 logn 이었던거로 기억하는데, 혹시 어떻게 n으로 도출하셨는지 알려주실수 있을까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

n개의 노드를 순회하며 각각 heap push를 하니 말씀하신 것 처럼 n * log n 이 맞습니다. 주석 복붙하다 빼먹은 것 같네요. 리뷰 감사합니다.

if curr_node.left is not None:
stack.append(curr_node.left)
if curr_node.right is not None:
stack.append(curr_node.right)

result = visited[0]
for _ in range(k):
result = heappop(visited)

return result

"""
Runtime: 43 ms (Beats 69.91%)
Analyze Complexity: O(n)
Memory: 19.46 MB (Beats 60.94%)
"""
def solve_2(self, root: Optional[TreeNode], k: int) -> int:
vals = []

def inorder_traverse(root: Optional[TreeNode]):
if root is None:
return

if len(vals) >= k:
return
Comment on lines +51 to +52
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 조건으로 빠르게 탐색을 마칠 수 있어 정말 좋네요! 👍


inorder_traverse(root.left)
vals.append(root.val)
inorder_traverse(root.right)

inorder_traverse(root)
return vals[k - 1]


class _LeetCodeTCs(TestCase):
def test_1(self):
root = TreeNode(
val=3,
left=TreeNode(
val=1,
left=None,
right=TreeNode(
val=2,
left=None,
right=None,
)
),
right=TreeNode(
val=4,
left=None,
right=None
)
)

k = 1
output = 1
self.assertEqual(Solution.kthSmallest(Solution(), root, k), output)

def test_2(self):
root = TreeNode(
val=5,
left=TreeNode(
val=3,
left=TreeNode(
val=2,
left=TreeNode(
val=1
)
),
right=TreeNode(
val=4
)
),
right=TreeNode(
val=6
)
)
k = 3
output = [3]
self.assertEqual(Solution.kthSmallest(Solution(), root, k), output)


if __name__ == '__main__':
main()
41 changes: 41 additions & 0 deletions kth-smallest-element-in-a-bst/EGON.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Foundation

public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}

class Solution {

/*
Runtime: 28 ms (Beats 46.95%)
Analyze Complexity: O(n)
Memory: 16.52 MB (Beats 53.05%)
*/
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
func inorderTraverse(_ root: TreeNode?, _ k: Int) {
guard let root = root, visited.count < k else {
return
}

inorderTraverse(root.left, k)
if visited.count < k {
visited.append(root.val)
}
inorderTraverse(root.right, k)
}

var visited: [Int] = []
inorderTraverse(root, k)

return visited[k - 1]
}
}
72 changes: 72 additions & 0 deletions number-of-1-bits/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from unittest import TestCase, main


class Solution:
def hammingWeight(self, n: int) -> int:
return self.solve_4(n=n)

"""
Runtime: 26 ms (Beats 97.13%)
Analyze Complexity: O(log n), bin(int)가 O(log(n))
Memory: 16.56 MB (Beats 22.67%)
"""
def solve_1(self, n: int) -> int:
return bin(n).count('1')

"""
Runtime: 31 ms (Beats 85.00%)
Analyze Complexity: O(log n)
Memory: 16.60 MB (Beats 22.67%)
"""
def solve_2(self, n: int) -> int:
hamming_weight = 0
while n:
hamming_weight += n % 2
n = n >> 1
return hamming_weight

"""
Runtime: 30 ms (Beats 88.73%)
Analyze Complexity: O(k), k는 2진수의 1의 갯수 (== O(log(n)))
Memory: 16.56 MB (Beats 22.67%)
"""
# Brian Kernighan's Algorithm
def solve_3(self, n: int) -> int:
hamming_weight = 0
while n:
n &= (n - 1)
hamming_weight += 1
return hamming_weight

"""
Runtime: 36 ms (Beats 53.56%)
Analyze Complexity: O(k), k는 2진수의 1의 갯수 (== O(log(n)))
Memory: 16.55 MB (Beats 22.67%)
"""
def solve_4(self, n: int) -> int:
hamming_weight = 0
while n:
hamming_weight += n & 1
n >>= 1
return hamming_weight


class _LeetCodeTCs(TestCase):
def test_1(self):
n = 11
output = 3
self.assertEqual(Solution.hammingWeight(Solution(), n=n), output)

def test_2(self):
n = 128
output = 1
self.assertEqual(Solution.hammingWeight(Solution(), n=n), output)

def test_3(self):
n = 2147483645
output = 30
self.assertEqual(Solution.hammingWeight(Solution(), n=n), output)


if __name__ == '__main__':
main()
32 changes: 32 additions & 0 deletions number-of-1-bits/EGON.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Foundation

class Solution {
func hammingWeight(_ n: Int) -> Int {
return solve_2(n)
}

/*
Runtime: 5 ms (Beats 38.73%)
Analyze Complexity: O(k), k는 2진수의 1의 갯수
Memory: 14.88 MB (Beats 98.27%)
*/
func solve_1(_ n: Int) -> Int {
return n.nonzeroBitCount
}

/*
Runtime: 3 ms (Beats 65.90%)
Analyze Complexity: O(k), k는 2진수의 1의 갯수
Memory: 15.08 MB (Beats 89.02%)
*/
func solve_2(_ n: Int) -> Int {
var num = n
var hammingWeight = 0
while 0 < num {
num &= num - 1
hammingWeight += 1
}

return hammingWeight
}
}
Loading