https://leetcode.com/problems/linked-list-cycle/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
h1 = head
h2 = head.next
while h1 and h2:
if h1 == h2:
return True
h1 = h1.next if h1.next else h2.next
h2 = h2.next.next if h2.next and h2.next.next else h1.next
return False
거북이와 토끼인가 slow and fast 를 이용해서
h1
은 한 노드씩 천천히 움직이고 h2
는 두 노드씩 빠르게 움직여서
둘이 같은 노드를 가리키면 return True
class Solution:
def hasCycle(self, head: ListNode) -> bool:
h1 = head
h2 = head
while h2 and h2.next:
h1 = h1.next
h2 = h2.next.next
if h1 == h2:
return True
return False
이게 더 깔끔하니까 이걸로 외워두자!!
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
s = set()
while head is not None:
if head not in s:
s.add(head)
else:
return True
head = head.next
return False
이거는 한번 만나본 노드들을 s
에 넣어서 또 만났을 때 return True 해주는 방식
https://leetcode.com/problems/min-stack/
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, val: int) -> None:
self.stack.append(val)
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return min(self.stack)
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
문제 고대로...
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.A = []
self.M = []
def push(self, val: int) -> None:
self.A.append(val)
self.M.append(val if not self.M else min(val, self.M[-1]) )
def pop(self) -> None:
self.A.pop()
self.M.pop()
def top(self) -> int:
return self.A[-1]
def getMin(self) -> int:
return self.M[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
더 빠른 솔루션
두개의 리스트를 사용해서 A
에는 push 순서대로 넣고
M
에는 push 될 때마다 그 순간의 최솟값만 저장
https://leetcode.com/problems/set-matrix-zeroes/
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])
r = set()
c = set()
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
r.add(i)
c.add(j)
for i in range(m):
if i in r:
for j in range(n):
matrix[i][j] = 0
for j in range(n):
if j in c:
for i in range(m):
matrix[i][j] = 0
0 인 값의 row, column 인덱스를 r
, c
에 각각 넣어줘서
해당하는 행, 렬을 모두 0 으로 바꿔줌
https://leetcode.com/problems/sort-colors/
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
for j in range(i+1, 0, -1):
if nums[j] < nums[j-1]:
nums[j], nums[j-1] = nums[j-1], nums[j]
else:
break
전체 길이가 최대 300 이라 얼마 걸리지 않을 것 같아서...
i
값이 i+1
값 보다 크면 더 작은 i+1
값을 앞쪽으로 옮겨줌
1 은 그대로 두고 0 과 2 만 앞 뒤로 옮기는 방법도 생각남
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
low,mid,high = 0,0,len(nums)-1
while(mid<=high):
if nums[mid] == 0:
nums[low],nums[mid] = nums[mid],nums[low]
low+=1
mid+=1
elif nums[mid] == 1:
mid+=1
else:
nums[mid],nums[high] = nums[high],nums[mid]
high-=1
색깔이 0, 1, 2 만 있으므로 0 은 low, 1 은 mid, 2 는 high 를 맡음
중간 값이
0 이면 왼쪽 끝으로 가야하니까 low
값과 mid
값 바꿔주기 & low, mid + 1
1 이면 그대로 있으면 되므로 mid+1
2 면 오른쪽 끝으로 가야하니까 mid
값과 high
값 바꿔주기 & high - 1