X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other (on this case they are rotated in a different direction, in other words 2 or 5 gets mirrored); 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.
Now given a positive number N, how many numbers X from 1 to N are good?
class Solution:
def rotatedDigits(self, N: int) -> int:
# 119 -> 611 이 되는줄 알았는데 자리마다 rotate 네요..ㅎ 119 -> 116
no = ['3','4','7']
def rotate(ch):
if ch == '0' or ch == '1' or ch == '8':
return ch
if ch == '2':
return '5'
if ch == '5':
return '2'
if ch == '6':
return '9'
if ch == '9':
return '6'
cnt = 0
for i in range(1, N+1):
string = str(i)
new = ""
isDigit = 0
for j in range(len(string)):
if string[j] in no:
isDigit = 0
break
new += rotate(string[j])
isDigit = 1
if isDigit and new != string:
cnt += 1
return cnt
1 ~ N
까지 숫자들을 string 으로 바꿔서 각 자릿수마다 rotate
해줌
rotate 전후의 값이 같은지 비교
숫자에 3, 4, 7 이 있는 경우는 isDigit = 0 으로 해줘서 제외시킴
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
maxd = 0
closed = []
for i in range(len(seats)):
if seats[i] == 1:
closed.append(i)
for i in range(len(seats)):
if seats[i] == 0:
closed.append(i)
closed.sort()
idx = closed.index(i)
distance = 0
left = -1
right = -1
if idx-1 >= 0:
left = i - closed[idx-1]
if idx+1 < len(closed):
right = closed[idx+1] - i
if left == -1 or right == -1:
distance = max(left, right)
elif left == -1 and right == -1:
distance = 0
else:
distance = min(left, right)
maxd = max(distance, maxd)
closed.pop(idx)
return maxd
1 값인 인덱스들만 closed
리스트에 넣어줌
다시 반복문 돌려서 값이 0 일 때의 인덱스를 closed
에 임시로 넣은 후,
앞뒤 값과의 차이를 구해서 maxd
에 업데이트 해주고 임시로 넣은 값은 pop