본문 바로가기

Python191

[LeetCode] Valid Palindrome II https://leetcode.com/problems/valid-palindrome-ii/submissions/ Valid Palindrome II - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 투 포인터를 활용하면 되는 문제 class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ # Time: O(n) # Space: O(n) left, right = 0,.. 2022. 4. 2.
Python이 느린 이유? Python이 느린 이유. 지금까지 공부했을 때는 그냥 인터프리터 언어라서~ GIL 때문에~ 이러면서 적당히 넘어갔었는데, 찾아보며 하나하나 공부하다 보니 심오한(?) 내용들이 많았다 일단 내가 이해한 Python이 느린 이유를 간단하게 적고 조금씩 자세하게 추가 해 나가도록 해야겠다. Python은 인터프리터 언어인가요? 나의 생각은 반만 인터프리터 사실 인터프리터, 컴파일러 언어라는게 상당히 애매모호한 개념이다. 1. 사실 Python이 느린 게 아니라 Python의 표준 구현체인 Cpython이 느린 것. - Cpython 과 pypy의 차이 + 구현체가 어떻게 동작하길래? 2. 인터프리터, 컴파일러의 차이 (컴파일이 의미하는 게 뭐길래?) - 사실 Python도 어떻게 보면 컴파일 언어고 어떻게 .. 2022. 4. 2.
[LeetCode] Search a 2D Matrix https://leetcode.com/problems/search-a-2d-matrix/ Search a 2D Matrix - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 정렬되어 있는 게 이진 탐색으로 풀어주세요~ 하는 조건이다. 데이터는 매트릭스 형태이기 때문에 이에 맞춰 수정해주면 된다. 재귀로 풀었다. 나의 풀이 class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) ->.. 2022. 3. 30.
[LeetCode] Design Circular Queue (스택으로 원형 큐 구현) https://leetcode.com/problems/design-circular-queue/ Design Circular Queue - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 투 포인터 개념으로 풀면 된다. class MyCircularQueue: def __init__(self, k: int): self.q = [None]*k self.head = 0 self.tail = 0 self.size = k def enQueue(self, value: int.. 2022. 3. 29.
[LeetCode] Implement Queue using Stacks(스택으로 큐 구현) https://leetcode.com/problems/implement-queue-using-stacks/ Implement Queue using Stacks - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 스택을 두 개 사용해서 큐를 구현하는 문제 나의 풀이 class MyQueue: def __init__(self): self.s1 = list() self.s2 = list() def push(self, x: int) -> None: self.s1.appe.. 2022. 3. 29.
[LeetCode] Implement Stack using Queues(큐로 스택 구현) https://leetcode.com/problems/implement-stack-using-queues/ Implement Stack using Queues - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 큐로 스택을 구현하는 근본 문제 push 할 때 append 해주고 기존에 queue에 있던 원소는 popleft 이후 다시 큐의 맨 뒤로 줄줄이 붙여주면 된다. 요소 삽입 시 시간복잡도가 O(N)이 되어 다소 비효율적이긴 하지만, 큐로 스택을 구현할 수 .. 2022. 3. 29.
[LeetCode] Daily Temperatures https://leetcode.com/problems/daily-temperatures/ Daily Temperatures - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 어떤 시간의 흐름에 따라 풀이하는 건 스택을 활용하면 쉽게 풀 수 있는 것 같다. class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: stack = [] answer = [0] * len(temp.. 2022. 3. 29.
[LeetCode] Remove Duplicate Letters https://leetcode.com/problems/remove-duplicate-letters/ Remove Duplicate Letters - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com class Solution: def removeDuplicateLetters(self, s: str) -> str: last_occ = {} visited = set() stack = [] for i in range(len(s)): last_occ[s[i]] = i fo.. 2022. 3. 29.
[LeetCode] Number of Islands https://leetcode.com/problems/number-of-islands/ Number of Islands - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 매우 유명한 섬 문제 dfs로 풀이했다 class Solution: def numIslands(self, grid: List[List[str]]) -> int: move = [(0,1),(0,-1),(1,0),(-1,0)] def OOB(x, y): return x=len(grid) or y=l.. 2022. 3. 25.
[LeetCode] Two City Scheduling https://leetcode.com/problems/two-city-scheduling/ Two City Scheduling - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 쉬운줄 알았는데 은근히 까다로운 문제다. 처음에는 DP인가? 했다가 완전탐색인가? 했는데 최대 연산이 200! / 100! * 100! 인걸 보고 아닌 것을 깨닫고 그리디로 풀어봤다. 일단 최소한의 비용이 드는 승객들을 더하고 균형을 맞출 때에는 A와 B의 차이가 적은 순서대로 더해줘서 .. 2022. 3. 25.
[LeetCode] Valid Parentheses https://leetcode.com/problems/valid-parentheses/ Valid Parentheses - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 괄호가 정상적인지 찾는 스택의 대표 문제 class Solution: def isValid(self, s: str) -> bool: types = { ')' : '(', ']' : '[', '}': '{' } stack = [] for par in s: if par in types: if not.. 2022. 3. 25.
[LeetCode] Swap Nodes in Pairs https://leetcode.com/problems/swap-nodes-in-pairs/ Swap Nodes in Pairs - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 짝을 이뤄서 노드를 변경하는 것 value 값을 변경하면 안된다. 1 2 까지는 괜찮은데 3 4 를 변경할때 1의 next가 3이 아닌 4가 되어야 해서 이 부분에서 신경을 써줘야 함. 반복문을 이용한 풀이 class Solution: def swapPairs(self, head: Opt.. 2022. 3. 24.
[LeetCode] Boats to Save People https://leetcode.com/problems/boats-to-save-people/ Boats to Save People - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 보트에 사람을 실을 수 있고(최대 두 명) 무게는 limit 까지만 최소한으로 움직이는 횟수를 구하는 문제 내 풀이 정렬 + 투 포인터를 활용해서 풀었다. class Solution: def numRescueBoats(self, people: List[int], limit: int) .. 2022. 3. 24.
[LeetCode] Add Two Numbers https://leetcode.com/problems/add-two-numbers/ Add Two Numbers - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 연결 리스트를 뒤집어서 더한 값을 다시 뒤집어서 반환 내 풀이 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next cla.. 2022. 3. 23.
[LeetCode] Reverse Linked List https://leetcode.com/problems/reverse-linked-list/ Reverse Linked List - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 연결 리스트를 뒤집으면 된다. 단순한 문젠데 뭔가 실제로 해보려니까 한동안 뇌 정지 왔다. 역시 아직 부족하다 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # se.. 2022. 3. 23.