221120 항해99 14일차 알고리즘 문제풀이

요니링 컴터 공부즁·2022년 11월 21일
0
  1. 문자열 내 마음대로 정렬하기

내 답안
: 푸는데 엄청나게 오래 걸리긴 했지만 결국 풀었다,, 속도도 빠름,, 근데 변수가 자꾸 생겨서 디버깅 하는데 힘들었땅 그래도 재밌었다 흐흐 앞으론 짧게 하는걸 연습해야징,,

function solution(strings, n) {

      strings.sort((a, b) => a[n] > b[n] ? 1 : -1)

      let answer = []
      let i = 0
      let identical = []
      for (let j = 1; j < strings.length; j++) {
        i = j - 1
        if (strings[i][n] === strings[j][n]) {
          if (identical.length === 0) {
            identical.push(strings[i])
          }
          identical.push(strings[j])

          if (j !== strings.length - 1) continue
        }

        if (identical.length !== 0) {
          identical.sort()
          if (answer.length !== 0) {
            answer.length = answer.length - 1
          }
          answer.push(...identical)
          identical = []

          if (j < strings.length - 1) {
            j--
          } else {
            answer.push(strings[strings.length - 1])
          }

        } else {
          if (answer.length === 0) {
            answer.push(strings[i])
          }
          answer.push(strings[j])
        }
      }

      if (answer.length > strings.length) {
        answer.length = answer.length - 1
      }

      return answer
    }

모범답안
: 제일 위에 있던 모범 답안은 localeCompare이라는 메소드를 써서 한줄로 엄청 간단하게 하긴 했는데, 넘 느리게 돌아가서 효율성이 떨어지는 것으로 보였음,, 그래서 그 다음 답안을 가져왔다. 이 답안이 내가 처음에 쓰고 싶었던 답,, 근데 callback fucntion을 어떻게 수정하는지 모르겠어서 위에처럼 긴 코드가 됐삼,, 이렇게 쓰는거구낭!!

function solution(strings, n) {
    return strings.sort((a, b) => {
        const chr1 = a.charAt(n);
        const chr2 = b.charAt(n);

        if (chr1 == chr2) {
            return (a > b) - (a < b);
        } else {
            return (chr1 > chr2) - (chr1 < chr2);
        }
    })
}

0개의 댓글