어떤 정수 X에 대해서 쥐의 몸집 크기가 [X-2,X+2] 구간에 속하는 쥐가 가장 많을 때, 그 중 작은 X값이 대표값이 됩니다
몸집이 최대 10만개인데, for문으로 x=1부터 시작해서, 쥐 리스트에 x일 때 범위의 값이 있는지 확인하는건 무조건 시간초과가 뜰 것이라고 생각 (x값 -> 몸집 유무 탐색)
역으로, 쥐 리스트에 있는 몸집 값이 영향을 미칠 수 있는 x들을 생각하는 방식으로 해결 (몸집 탐색 -> 영향을 미치는 x값 기록)
코드
def central_dict(lst):
weight_dict = {}
for x in lst:
for i in range(x-2,x+3): #x-2,x-1,x,x+1,x+2
if i not in weight_dict.keys():
weight_dict[i] = 1
else:
weight_dict[i]+=1
return weight_dict
def find_max_key(weight_dict):
max_value = max(weight_dict.values()) #max몸무게를 가지고
max_keys = [key for key, value in weight_dict.items() if value == max_value] #max몸무게를 가지는 key값들을 리스트에 저장한 후
return min(max_keys) #그 중 최소값 반환
n = int(input())
A_lst = list(map(int,input().split()))
B_lst = list(map(int,input().split()))
central_A= central_dict(A_lst)
central_B= central_dict(B_lst)
result_key_A = find_max_key(central_A)
result_key_B = find_max_key(central_B)
print(result_key_A,result_key_B)
if result_key_A > result_key_B:
print("good")
else:
print("bad")
첨언
리스트 컴프리헨션을 통해 " 어떤 정수 X에 대해서 쥐의 몸집 크기가 [X-2,X+2] 구간에 속하는 쥐가 가장 많을 때, 그 중 작은 X값이 대표값이 됩니다" 조건에서 "그 중 작은 X값"이라는 조건을 처리하였다.