본문 바로가기

Algorithm101

[LeetCode] 35 | Search Insert Position 35 | Search Insert Position https://leetcode.com/problems/search-insert-position/ 작성 코드 class Solution: def searchInsert(self, nums: List[int], target: int) -> int: for idx, value in enumerate(nums): if value >= target: return idx return len(nums) nums 를 돌면서 taget 값보다 value 값이 클 때가 삽입할 경우이므로 return 만약 for문을 돌아도 return이 안 됐다면 제일 마지막에 삽입해야하는 경우이므로 len(nums) return 이상 코드 이진 탐색 구현 class Solution: de.. 2022. 4. 8.
[연결 리스트] 팰린드롬 연결 리스트 234 | Palindrome Linked List https://leetcode.com/problems/palindrome-linked-list/ 이상 코드 리스트 변환 class Solution: def isPalindrome(self, head: ListNode) -> bool: q: List = [] if not head: return True node = head # 리스트 변환 while node is not None: q.append(node.val) node = node.next # 팰린드롬 판별 while len(q) > 1: if q.pop(0) != q.pop(): return False return True 데크를 이용한 최적화 class Solution: def isPalindro.. 2022. 4. 6.
[LeetCode] 1162 | As Far from Land as Possible 1162 | As Far from Land as Possible https://leetcode.com/problems/as-far-from-land-as-possible/ 작성 코드 접근 방법 0인 grid[x][y]에서 가장 가까운 1 값까지의 거리를 저장해서 max 값을 return import collections class Solution: def maxDistance(self, grid: List[List[int]]) -> int: counts = -1 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: q = collections.deque() q.append([i, j, 0, []]) while q: x, .. 2022. 4. 5.
[LeetCode] 1020 | Number of Enclaves 1020 | Number of Enclaves https://leetcode.com/problems/number-of-enclaves/ 작성 코드 접근 방법 boundary 경계에 있는 원소들에 접근하여 인접 요소들을 0(물)으로 변환함 남은 grid 중 1을 count class Solution: def numEnclaves(self, grid: List[List[int]]) -> int: def dfs_boundary(x, y): if x = len(grid) or y = len(grid[0]) or grid[x][y] == 0: return grid[x][y] = 0 dfs_boundary(x - 1, y) dfs_boundary(x + 1, y) dfs_boun.. 2022. 4. 4.
[LeetCode] 11 | Container With Most Water 11 | Container With Most Water https://leetcode.com/problems/container-with-most-water/ 작성 코드 class Solution: def maxArea(self, height: List[int]) -> int: water = 0 for j in range(len(height)): for k in range(j, len(height)): water = max(water, (k - j) * min(height[j], height[k])) return water 시간 초과 발생 이상 코드 class Solution: def maxArea(self, height: List[int]) -> int: start, end = 0, len(height).. 2022. 4. 1.
[LeetCode] 1905 | Count Sub Islands 1905 | Count Sub Islands https://leetcode.com/problems/count-sub-islands/ 작성 코드 class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: def dfs(x, y): if x = len(grid2) or y = len(grid2[0]) or grid2[x][y] == 0: return [] grid2[x][y] = 0 return [[x, y]] + dfs(x - 1, y) + dfs(x + 1, y) + dfs(x, y - 1) + dfs(x, y + 1) answer = 0 islands .. 2022. 3. 30.
반응형