나의 첫번째 풀이
아주 제너럴한 접근방식이었을 것 같다..
def number_of_love(X,Y):
first = list(X)
second = list(Y)
common = []
for i in first:
if i in second:
common.append(i)
second.remove(i)
if len(common) == 0:
return str(-1)
elif int(''.join(map(str, common))) == 0:
return str(0)
else:
common.sort(reverse=True)
new_number = int(''.join(map(str, common)))
return str(new_number)
결과는 실패. 테케 11 -15에서 타임아웃이 계속 나와서 조언을 구했더니, sort 가 리소스를 많이 먹는다는 피드백을 받았다.
나의 두번째 풀이
def number_of_love(X,Y):
first = list(X)
second = list(Y)
common = []
for i in first:
if i in second:
common.append(i)
second.remove(i)
if len(common) == 0:
return str(-1)
new_number = 0
while common:
max_num = max(common)
new_number = new_number * 10 + int(max_num)
common.remove(max_num)
if new_number == 0:
return str(0)
else:
return str(new_number)
sort 를 안쓰기 위해 무한루프를 냅다 써봤다.. 하나씩 제일 큰걸 먼저 더하고 더한거 제거하는 식으로 돌렸다. 당연히 실패. 시간복잡도가 어쩌면 sort 쓰는것보다 더 늘었을지도..?
결국 찾은 방법!!
sort 를 안 쓰고 내림차순 정렬해 더할 수 있는 법
count 를 쓰면 된다
혹은 패키지로 그냥 collection 을 쓰는 케이스도 있었음
def solution(X, Y):
answer = ''
for i in range(9,-1,-1) :
answer += (str(i) * min(X.count(str(i)), Y.count(str(i))))
if answer == '' :
return '-1'
elif len(answer) == answer.count('0'):
return '0'
else :
return answer
728x90
'코딩테스트 > python' 카테고리의 다른 글
[python][프로그래머스_lv1] 완주하지 못한 선수 (feat. 해시테이블) (0) | 2023.03.16 |
---|---|
[python][프로그래머스_lv1] 체육복 (feat. 탐욕법) (0) | 2023.01.06 |
[python][프로그래머스_lv1] 로또의 최고 순위와 최저 순위 (0) | 2023.01.05 |
[python][코딩테스트_lv1] 다트 게임 (0) | 2022.12.30 |
[python][프로그래머스_lv1] 푸드 파이트 대회 (0) | 2022.12.30 |