코딩테스트 연습 27: [프로그래머스] 완주하지 못한 선수

gyomni·2022년 1월 26일
0

Algorithm

목록 보기
27/33
post-thumbnail

출처 : 프로그래머스
사용 언어 : JavaScript

초기 코드

function solution(participant, completion) {
    var answer = '';
    return answer;
}

내가 작성한 코드

function solution(participant, completion) {
    let answer=participant;
    let count =0;
    for(let i=0;i<participant.length;i++){
       for(let j=0;j<completion.length;j++){
           if( participant[i]===completion[j]){
               
               delete participant[i]
               delete completion[j]
           }
       } 
       
    }
    return String(participant.filter(n=>typeof(n)==='string'));
}


결과값은 맞았지만
효율성 테스트는 모조리 실패....?ㅜㅜ
시간 복잡도를 고려했을 때 for 이중문이 화근이 된듯하다

다시 작성한 코드

function solution(participant, completion) {
    
    participant.sort();
    completion.sort();
    for(let i=0;participant.length;i++){
      if( participant[i]!== completion[i]){
          return participant[i]
      }
    }

}


sort로 정렬해서 인덱스 값이 다른 값만 반환해주니 간단한 풀렸다

다른 사람 풀이

function solution(participant, completion) {
    const map = new Map();

    for(let i = 0; i < participant.length; i++) {
        let a = participant[i], 
            b = completion[i];

        map.set(a, (map.get(a) || 0) + 1);
        map.set(b, (map.get(b) || 0) - 1);
    }

    for(let [k, v] of map) {
        if(v > 0) return k;
    }

    return 'nothing';
}

🙍‍♀️ 📝

Map object
: ECMAScript 6에서 값들을 매핑하기 위한 새로운 데이터 구조를 소개 하고 있다.
그중 하나인 Map객체는 간단한 키와 값을 서로 연결(매핑)시켜 저장하며 저장된 순서대로 각 요소들을 반복적으로 접근할 수 있도록 한다.
Map객체에 저장되어 있는 각 요소들을 [키, 값] 형태의 배열로 반복적으로 반환해주는 for...of를 사용할 수 있다.

var sayings = new Map();

sayings.set("dog", "woof");
sayings.set("cat", "meow");
sayings.set("elephant", "toot");
sayings.size; // 3

sayings.get("fox"); // undefined
sayings.has("bird"); // false
sayings.delete("dog");

for (var [key, value] of sayings) {
  console.log(key + " goes " + value);
}
// "cat goes meow"
// "elephant goes toot"

Setobject
: Set객체는 값들의 집합이다.
입력된 순서에따라 저장된 요소를 반복처리할 수 있다.
Set은 중복된 값을 허용하지 않는다. 따라서 특정 값은 Set내에서 하나만 존재 하게 된다.

var mySet = new Set();

mySet.add(1);
mySet.add("some text");
mySet.add("foo");

mySet.has(1); // true

mySet.delete("foo");
mySet.size; // 2

for (let item of mySet) console.log(item);
// 1
// "some text"

참고 : 링크텍스트

profile
Front-end developer 👩‍💻✍

0개의 댓글