본문 바로가기

Programming207

[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.
[LeetCode] Broken Calculator https://leetcode.com/problems/broken-calculator/ Broken Calculator - 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 brokenCalc(self, startValue: int, target: int) -> int: q : Deque = collections.deque() q.append((startValue, 0)) whil.. 2022. 3. 23.
[LeetCode] Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/ Merge Two Sorted Lists - 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 정렬된 두 연결 리스트를 크기 순서대로 정렬하여 병합하는 문제 1. list1과 list2를 비교해 주면서 merge_list에 추가 2. 원소가 남은 친구들을 추가 # Definition for singly-linked list. # class ListNode: # def _.. 2022. 3. 23.
[LeetCode] Palindrome Linked List https://leetcode.com/problems/palindrome-linked-list/ Palindrome 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 Deque를 활용하면 popleft도 O(1) 이므로 성능 향상 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self... 2022. 3. 23.
python 다중 할당 동작방식 python 다중 할당의 동작 방식에 대해 어렴풋이 이해하고 있었는데, 이번 기회에 확실하게 짚고 넘어가야겠다. 일단 파이썬에서는 다중 할당(Multiple Assignment)을 지원한다. 이는 2개 이상의 값을 2개 이상의 변수에 동시에 할당하는 것을 말한다. a, b = 1, 2 >>> a 1 >>> b 2 위와 같이 a와 b 변수 각각의 값을 1, 2로 할당해 주었다. 좀 더 복잡한 경우에 어떻게 동작하는지 테스트해보았다. 아래 코드를 보자. class SingleLinkedList: def __init__(self, name, val=0, next=None) -> None: self.name = name self.val = val self.next = next def __repr__(self):.. 2022. 3. 23.
python typing optional python에서는 굳이 타입을 명시하지 않아도 duck typing (동적 타이핑)을 통해 객체의 타입이 결정된다. 이는 편리하다는 장점이 있지만, 코드가 많아지게 되면 뭐가 뭔지 알아보기 힘들다는 단점이 있다. 이를 보완하기 위해 파이썬에서는 typing을 지정할 수 있게 typing 모듈을 제공한다. https://docs.python.org/3/library/typing.html typing — Support for type hints — Python 3.10.3 documentation Note The Python runtime does not enforce function and variable type annotations. They can be used by third party tools .. 2022. 3. 23.
[LeetCode] Reverse String https://leetcode.com/problems/reverse-string/submissions/ Reverse String - 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 reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0,.. 2022. 2. 28.
[LeetCode] Valid Palindrome https://leetcode.com/problems/valid-palindrome/ Valid Palindrome - 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 유효한 펠린드롬인지 확인하는 문제 Deque를 활용해서 풀이 가능 class Solution: def isPalindrome(self, s: str) -> bool: strs: Deque = collections.deque() for char in s: if char.isalnum(): strs.a.. 2022. 2. 25.
[프로그래머스] 110 옮기기(Python) https://programmers.co.kr/learn/courses/30/lessons/77886 코딩테스트 연습 - 110 옮기기 0과 1로 이루어진 어떤 문자열 x에 대해서, 당신은 다음과 같은 행동을 통해 x를 최대한 사전 순으로 앞에 오도록 만들고자 합니다. x에 있는 "110"을 뽑아서, 임의의 위치에 다시 삽입합니다. 예를 programmers.co.kr 문제의 핵심은 111보다 110이 앞에 와야 함. def solution(s): answer = [] for string in s: stack = [] counting = 0 for st in string: if(len(stack) >= 2 and stack[-1] == '1' and stack[-2] =='1' and st =='0'):.. 2022. 2. 12.
[프로그래머스] 블록 게임(Python) https://programmers.co.kr/learn/courses/30/lessons/42894 코딩테스트 연습 - 블록 게임 [[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,4,0,0,0],[0,0,0,0,0,4,4,0,0,0],[0,0,0,0,3,0,4,0,0,0],[0,0,0,2,3,0,0,0,5,5],[1,2,2,2,3,3,0,0,0,5],[1,1,1,0,0,0,0,0,0,5]] 2 programmers.co.kr 구현이 좀 까다로웠던 문제다. 처음에 블록 게임을 테트리스처럼 생각해서 헷갈렸는데 검정 블록은 아래로 쭉 가는 방향으로만 쌓을 수 있다. 1. 매번.. 2022. 2. 10.