diff --git a/linked-list-cycle/devyejin.py b/linked-list-cycle/devyejin.py new file mode 100644 index 000000000..bcedbd2e0 --- /dev/null +++ b/linked-list-cycle/devyejin.py @@ -0,0 +1,35 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +from typing import Optional + +# time complexity O(n) +# space complexity O(1) +class Solution: + def hasCycle(self, head: Optional[ListNode]) -> bool: + slow, fast = head, head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + if slow == fast: + return True + return False + + +# time complexity O(n) +# space complexity O(n) +# class Solution: +# def hasCycle(self, head: Optional[ListNode]) -> bool: +# visited = set() +# while head: +# if head in visited: +# return True +# visited.add(head) +# head = head.next +# return False + + diff --git a/maximum-product-subarray/devyejin.py b/maximum-product-subarray/devyejin.py new file mode 100644 index 000000000..b2034a76f --- /dev/null +++ b/maximum-product-subarray/devyejin.py @@ -0,0 +1,19 @@ +from typing import List + +# time O(n), space O(1) +class Solution: + def maxProduct(self, nums: List[int]) -> int: + max_prod = nums[0] + min_prod = nums[0] + result = nums[0] + + for i in range(1, len(nums)): + candidates = (nums[i], nums[i] * max_prod, nums[i] * min_prod) + max_prod, min_prod = max(candidates), min(candidates) + result = max(result, max_prod) + + return result + + + + diff --git a/pacific-atlantic-water-flow/devyejin.py b/pacific-atlantic-water-flow/devyejin.py new file mode 100644 index 000000000..fe8496730 --- /dev/null +++ b/pacific-atlantic-water-flow/devyejin.py @@ -0,0 +1,45 @@ +from typing import List +from collections import deque + +# time O(mn), saoce O(mn) +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + m, n = len(heights), len(heights[0]) + # 방문 배열 + pacific = [[False] * n for _ in range(m)] + atlantic = [[False] * n for _ in range(m)] + + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + + def bfs(r, c, visited): + queue = deque([(r, c)]) + visited[r][c] = True + + while queue: + r, c = queue.popleft() + + for dr, dc in directions: + new_r, new_c = r + dr, c + dc + if (0 <= new_r < m and 0 <= new_c < n + and not visited[new_r][new_c] + and heights[new_r][new_c] >= heights[r][c]): + visited[new_r][new_c] = True + queue.append((new_r, new_c)) + + for i in range(n): + bfs(0, i, pacific) + bfs(m - 1, i, atlantic) + for i in range(m): + bfs(i, 0, pacific) + bfs(i, n - 1, atlantic) + + result = [] + for i in range(m): + for j in range(n): + if pacific[i][j] and atlantic[i][j]: + result.append([i, j]) + + return result + + +