티스토리 뷰

반응형
깃허브 : https://github.com/miiingo/codility

Task description

원본 사이트 : https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/

 

OddOccurrencesInArray coding task - Learn to Code - Codility

Find value that occurs in odd number of elements.

app.codility.com

- A[N] 배열에는 홀수가 들어있으며 각 요소는 동일한 값을 가진 다른 요소(짝이 없는 요소여야함)와 쌍을 이룰 수 있음
- 짝을 이루지 않은 요소의 값 반환
- 가장 효율적인 알고리즘 작성
- A의 값 중 하나를 제외한 모든 값이 짝수 번 발생함 -> 짝을 이루지 않은 요소는 단 한 개 뿐!

 

Solution

// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    let element = new Set();
    
    for(let i in A){
        if(!element.has(A[i])){
            element.add(A[i]);
        }
        else{
            element.delete(A[i]);
        }
    }
    
    const result = [...element];
    return result[0];
}

- element라는 이름의 set을 생성
- 배열 A를 for문을 돌며 element set에 값이 없으면 해당 값을 추가하고, 있으면 해당 값을 지움
- 결국 element set에는 짝이 없는 요소의 값만 남게 됨 -> 항상 한 개의 값만 남음
- element set은 object 형태이기 때문에 그대로 return하면 오류 발생
- element set을 result Array로 변환한 후 result[0] 값을 return -> 한 개의 값만 있기 때문에 0번째 인덱스를 return

 

Result

 

Analysis

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함