본문 바로가기

알고리즘

OddOccurrencesInArray_Codility

문제

A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

For example, in array A such that:

A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9

the elements at indexes 0 and 2 have value 9,

the elements at indexes 1 and 3 have value 3,

the elements at indexes 4 and 6 have value 9,

the element at index 5 has value 7 and is unpaired.

Write a function:

function solution(A);

that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.

For example, given array A such that:

A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9

the function should return 7, as explained in the example above.

 

 

Assume that:

  • N is an odd integer within the range [1..1,000,000];
  • each element of array A is an integer within the range [1..1,000,000,000];
  • all but one of the values in A occur an even number of times.
  •  

 

풀이

function solution(A) {
    if (A.length > 0) {
        let map = new Map();
        for (let value of A) { 
            map.has(value) ? map.set(value, map.get(value)+1) : map.set(value, 1)  
        }

        for (var value of map) {
            if ((value % 2) !== 0) {
                return key;
            }
        }
    }
}

 

Map 객체 안에 Key는 A배열의 요소를, Value는 for문을 돌면서 map에 값이 있으면 1씩추가하였고,

값이 없으면 default인 1만 주었다.

예를 들면 A = [9, 3, 9, 3, 9, 7, 9]일때 Map 객체는 {9 ⇒ 4, 3 ⇒ 2, 7 ⇒1} 이런 구조로 저장할 수 있다.

Map 객체에서 value가 홀수인경우는 unpaired를 의미하기 때문에 value를 2로 나눴을 때 나머지가 생기는 경우를 찾는다.

 

다른 풀이

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에 값이 없으면 해당 값을 추가하고 있으면 해당 값을 지우는 접근 방식도 배울 수 있었다.

 

참고: miiingo 티스토리

'알고리즘' 카테고리의 다른 글

PermMissingElem_codility  (0) 2022.02.21
FrogJmp_codility  (0) 2022.02.18
CyclicRotation_Codility  (0) 2022.02.15
Remove Nth Node From End of List - leetcode  (0) 2021.11.04
Valid Anagram - leetcode  (0) 2021.10.08