본문 바로가기

LeetCode4

704, Binary Search class Solution: def search(self, nums: List[int], target: int) -> int: if not nums: return -1 l, r = 0, len(nums)-1 while l  풀이를 보면, 중간 값을 구하는 다른 방법을 확인할 수 있습니다.각 방식에 대해서 ChatGPT에게 물어보면,(l + r) // 2이 방법은 두 수의 합을 구한 후에 2로 나눈 후 소수점을 버립니다. (내림)이 방법은 가장 간단하지만, 중간 값이 매우 큰 경우에는 오버플로우가 발생할 수 있습니다.이 방법은 두 수의 차를 구한 후에 2로 나눈 후 소수점을 버립니다. (내림)그 결과를 l 에 더하여 중간 값을 찾.. 2024. 5. 23.
169, Majority Element class Solution: def majorityElement(self, nums: List[int]) -> int: std = len(nums) / 2 _map = {} for i in nums: try: _map[i] except KeyError: _map[i] = 0 finally: _map[i] += 1 if _map[i] > std: return i파이썬 스타일 가이드에 따라 가독성, 명확성, 간결성 있게 코드를 작성해보았다. from collection.. 2024. 5. 23.
235, Lowest Common Ancestor of a Binary Search Tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """가장 작은 부모 찾기 경우의 수: * P, Q가 부모 노드 왼쪽에만 존재하는 경우 * P, Q가 부모 노드 오른쪽에만 존재하는 경우 * P는 부모 노드 왼쪽, Q는 부모 노드 오른쪽에 존재하는 경우 * P 또는 Q 중 하나가 루트 노드에 존재하는 경우 LCA, Lowes.. 2024. 2. 25.
217, Contains Duplicate 1. 브루트 포스 class Solution: def containsDuplicate(self, nums: List[int]) -> bool: """brute force Time Complexity: O(n^2) Space Complexity: O(1) Returns: Time Limit Exceeded """ _len = len(nums) for i in range(_len-1): temp = nums[i] for j in range(i+1, _len): if temp == nums[j]: return True return False​ 2. 정렬 class Solution: def containsDuplicate(self, nums: List[int]) -> bool: """sort 파이썬의 내장함수 .. 2024. 2. 19.