본문 바로가기

Algorithm101

[LeetCode] 1254 | Number of Closed Islands 1254 | Number of Closed Islands https://leetcode.com/problems/number-of-closed-islands/ 작성 코드 접근 방법 for 문을 돌며 grid[x][y] = 0 인 곳은 dfs 으로 상하좌우 탐색 후, 한 번 돌면 count += 1 모든 면이 물(1)로 둘러 쌓여야 하기 때문에, 테두리에 grid[x][y] = 0 인 곳은 dfs 상하좌우 탐색 하여 1로 변환해줌 class Solution: def closedIsland(self, grid: List[List[int]]) -> int: def dfs(x, y): if (x = len(grid) or y = len(grid[0])) or grid[x][y].. 2022. 3. 29.
[LeetCode] 6 | Zigzag Conversion 6 | Zigzag Conversion https://leetcode.com/problems/zigzag-conversion/ 작성 코드 접근 방법 각 행에 반복되는 규칙을 찾아 인덱스로 저장하자 class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s elif numRows == 2: indexes = [] indexes += [s[index] for index in range(0, len(s), 2)] indexes += [s[index] for index in range(1, len(s), 2)] return ''.join(indexes) indexes = [] repeat = numRows + .. 2022. 3. 21.
[LeetCode] 695 | Max Area of Island 695 | Max Area of Island https://leetcode.com/problems/max-area-of-island/ 작성 코드 접근 방법 x축, y축을 돌며 1인 경우에 dfs 함수 호출 dfs 함수에서 해당 요소의 상하좌우 값 탐색 상하좌우 다 더한 값을 return class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: def dfs(x, y, a): # If over the index, finish if x = len(grid) or y = len(grid[0]) or grid[x][y] == 0: return 0 # assigned a value of 0, if visi.. 2022. 3. 17.
[해시 테이블] 상위 K 빈도 요소 347 | Top K Frequent Elements https://leetcode.com/problems/top-k-frequent-elements/ 작성 코드 접근 방법 Counter 객체를 활용하여 빈도수 정렬한 후 key 값 가져와서 k 만큼 슬라이싱한 배열을 return import collections class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: answer = [] a = collections.Counter(nums) for i in a: answer.append(i) if len(answer) == k: return answer a = Counter({0: 2, 3: 1, 1: 1}) 으로 잘 정.. 2022. 3. 17.
[해시 테이블] 중복 문자 없는 가장 긴 부분 문자열 3 | Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/ 작성 코드 접근 방법 for 문을 두 번 돌면서 해결 (시작 값, 끝 값) 임시 저장 변수 만들어줘서 끝 값이 중복인지 아닌지 확인 중복이면 break, 중복이 아니면 임시 저장 변수에 더해줌 임시 저장 변수의 len 을 append 가장 큰 max 값 append class Solution: def lengthOfLongestSubstring(self, s: str) -> int: subs = [] for i in range(len(s)): temp = s[i] for j i.. 2022. 3. 16.
[LeetCode] 1822 | Sign of the Product of an Array 1822 | Sign of the Product of an Array https://leetcode.com/problems/sign-of-the-product-of-an-array/ 작성 코드 class Solution: def arraySign(self, nums: List[int]) -> int: nums.sort() for idx, num in enumerate(nums): if num == 0: return 0 if num > 0: if idx % 2 == 0: return 1 else: return -1 return -1 접근 방법 sort 한 후 제일 처음에 나오는 양수 값의 인덱스 짝/홀에 따라 부호가 갈리지 않을까? 풀이 0이 하나라도 있으면 곱은 0이 되기 때문에 0 return num의.. 2022. 3. 15.
반응형