[Codility] [Javascript] OddOccurrencesInArray

2021. 2. 27. 22:03알고리즘/코딜리티

728x90
반응형
SMALL

Task description

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.

 

Write an efficient algorithm for the following assumptions:

  • 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.

 

 

🌈 OddOccurrencesInArray.js

 

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
31
32
33
34
35
36
37
38
39
40
41
42
var HashMap = function() {
    this.map = new Array();
};
 
HashMap.prototype = {
    put: function(key, value) {
        return this.map[key] = value;
    },
    get: function(key) {
        return this.map[key];
    },
    getOrDefault: function(key, defaultValue) {
        if (this.map[key]) {
            return this.map[key]
        } else {
            return defaultValue
        }
    }
};
 
/**
 * Find value that occurs in odd number of elements.
 * @param {*} A
 */
function solution(A) {
    let map = new HashMap();
 
    for(let i in A) {
        map.put(A[i], map.getOrDefault(A[i], 0+ 1);
    }
 
    let result = 0;
 
    for(let i in A) {
        // all but one of the values in A occur an even number of times.
        if (map.get(A[i]) % 2 != 0) {
            result = A[i];
        }
    }
 
    return result;
}
cs

 

 

👩‍💻 풀어보기 👨‍💻 https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/start/

 

Codility

Your browser is not supported You should use a supported browser for the test. Read more

app.codility.com

 

728x90
반응형
LIST