전에 풀었던 아마존 문제 였다^^
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec2[0] == rec2[2] or rec2[1] == rec2[3] or rec1[0] == rec1[2] or rec1[1] == rec1[3]:
return False
# rec2 의 bottom-left 가 overlap
if (rec1[0] < rec2[0] and rec1[2] > rec2[0]) and (rec1[1] < rec2[1] and rec1[3] > rec2[1]):
return True
# rec2 의 top-right 가 overlap
if (rec1[0] < rec2[2] and rec1[2] > rec2[2]) and (rec1[1] < rec2[3] and rec1[3] > rec2[3]):
return True
# rec2 안에 rec1 이 있을 때
if rec2[0] <= rec1[0] and rec2[1] <= rec1[1] and rec2[2] >= rec1[2] and rec2[3] >= rec1[3]:
return True
# rec2 의 bottom-right 가 overlap
if (rec1[0] < rec2[2] and rec1[2] > rec2[2]) and (rec1[1] < rec2[1] and rec1[3] > rec2[1]):
return True
# rec2 의 top-left 가 overlap
if (rec1[0] < rec2[0] and rec1[2] > rec2[0]) and (rec1[1] < rec2[3] and rec1[3] > rec2[3]):
return True
if (rec1[0] < rec2[2] and rec1[2] > rec2[0]) and (rec2[3] > rec1[1] and rec2[1] < rec1[3]):
return True
return False
저번에도 이렇게 모든 경우를 분류해서 했던 거 같은데...
이런 문제는 다신 만나고 싶지가 않네요...ㅎ
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec2[0] == rec2[2] or rec2[1] == rec2[3] or rec1[0] == rec1[2] or rec1[1] == rec1[3]:
return False
if rec1[0] >= rec2[2] or rec1[2] <= rec2[0] or rec2[3] <= rec1[1] or rec2[1] >= rec1[3]:
return False
return True
반대로 False
의 경우를 조건으로 잡으면 더 간단해진다..
A string s of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
class Solution:
def partitionLabels(self, s: str) -> List[int]:
result = []
count = collections.Counter(s)
cnt = 0
now = []
for i in range(len(s)):
if s[i] not in now:
now.append(s[i])
count[s[i]] -= 1
cnt += 1
zero = 0
for j in range(len(now)):
if count[now[j]] != 0:
zero = 0
break
zero = 1
if zero:
result.append(cnt)
now = []
cnt = 0
return result
각 문자들의 개수를 구함 => count
하나씩 보면서 at most 가 될 때까지 now
에 추가해줌
now
리스트의 값들의 개수가 모두 0
이 되면 result
에 update 후 초기화
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = {c: i for i, c in enumerate(s)}
j = anchor = 0
ans = []
for i, c in enumerate(s):
j = max(j, last[c])
if i == j:
ans.append(i - anchor + 1)
anchor = i + 1
return ans
Greedy
각 문자들의 마지막 위치값을 last
에 저장
j
에는 가장 마지막 인덱스를 update 해주고 그 지점이 나올 때까지 돌려줌 (i == j
)
at most 가 되면 ans
에 update
anchor
는 길이 계산에 사용