문제출처 :
https://school.programmers.co.kr/learn/courses/30/lessons/118666?language=javascript
1차작성 코드
function updateChoice(choice) { if(choice <= 3) { return -1*(4-choice) } else if (choice > 4) { return choice-4 } else { return 0 } } function solution(survey, choices) { let choice = choices.map((choose) => updateChoice(choose)) let score_dict = {"RT":0,"CF":0,"JM":0,"AN":0,} survey.forEach((ques,idx) => { if(ques == "AN" || ques == "NA") { score_dict["AN"] += ques[0] == "A" ? choice[idx] : -1*choice[idx] } else if(ques == "RT" || ques == "TR") { score_dict["RT"] += ques[0] == "R" ? choice[idx] : -1*choice[idx] } else if(ques == "FC" || ques == "CF") { score_dict["CF"] += ques[0] == "C" ? choice[idx] : -1*choice[idx] } else { score_dict["JM"] += ques[0] == "J" ? choice[idx] : -1*choice[idx] } }) let result = "" for(mbti in score_dict) { if(score_dict[mbti] <= 0) { result += mbti[0] } else { result += mbti[1] } } return result; }
2차작성 코드
function solution(survey, choices) { let score_dict = {"A":0,"N":0,"C":0,"F":0,"M":0,"J":0,"R":0,"T":0} survey.forEach((ques,idx) => { const acc = Math.abs(4-choices[idx]) if(choices[idx] > 4) { score_dict[ques[1]] += acc } else { score_dict[ques[0]] += acc } }) let result = "" result += score_dict["R"]-score_dict["T"]>=0 ? "R" : "T" result += score_dict["C"]-score_dict["F"]>=0 ? "C" : "F" result += score_dict["J"]-score_dict["M"]>=0 ? "J" : "M" result += score_dict["A"]-score_dict["N"]>=0 ? "A" : "N" return result; }
총평 : 두 코드의 시간복잡도는 확연히 차이가 난다. 경우의 수를 고려해보고 좀 더 빠르다고 생각하는 것에 집중해보자.