문제링크: 숫자짝꿍
✍🏻 Information
| content | |
|---|---|
| 언어 | python |
| 난이도 | ⭐️ |
| 풀이시간 | 60분 |
| 제출횟수 | ∞ |
| 인터넷검색유무 | no |
🍒 My Code
def solution(X, Y):
answer = ''
_X = [0 for i in range(10)]
_Y = [0 for i in range(10)]
cnt = [0 for i in range(10)]
for i in range(10):
_X[i]=X.count(str(i))
_Y[i]=Y.count(str(i))
cnt[i] = min(_X[i],_Y[i])
if sum(cnt)==0:
return "-1"
if sum(cnt[1:])==0:
return "0"
for i in range(10):
answer=str(i)*cnt[i]+answer
return answer
💡 What I learned
시간초과 해결하는데 꽤나 애썼다... 마지막 문제는 str(int(answer))로 return해서였다. -1,0 return하는 경우를 answer 만든 이후에 처리 안해주고(answer길이가 0이면 -1을 return해라 등) 앞에서 처리해주고 형변환 없이 answer만 return했더니 고쳐졌다. answer가 int길이를 넘어가는 경우 때문에 시간초과가 떴던것같다.
아래와 같은 풀이로 여러번 코드를 짰으나 일부 테케에서 다 시간초과 떴었다.
#풀이1
same = []
if len(X)<len(Y):
for i in X:
if i in Y:
same.append(i)
Y = Y.replace(i,'',1)
else:
for i in Y:
if i in X:
same.append(i)
X = X.replace(i,'',1)
same.sort(reverse=True)
for i in same:
answer+=i
#풀이2
_X, _Y = sorted(X), sorted(Y)
xpoint, ypoint = 0, 0
while xpoint<len(_X) and ypoint<len(_Y):
if _X[xpoint]>_Y[ypoint]:
ypoint+=1
elif _X[xpoint]<_Y[ypoint]:
xpoint+=1
else:
answer=_X[xpoint]+answer
xpoint+=1
ypoint+=1
if len(answer)==0:
return "-1"
if answer[0]=='0':
return "0"
return str(int(answer))