본문으로 바로가기

Description

아래의 조건을 만족하는 N개의 정수로 구성된 배열 A가 주어지면 쌍이 없는 요소의 값을 반환한다.

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:

class Solution { public int solution(int[] 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.

Solution 1. XOR 사용

public int solution(int[] A) {
        
    int len = A.length;
    for(int i=1; i < len; i++){
        A[i] = A[i]^A[i-1];
    }
    return A[len-1];
}

두개의 비트가 다를때만 1을 반환가고 같으면 0을 반환하는 XOR을 이용해 비트연산을 해줍니다. 배열에서 하나의 요소를 제외 하고 모두 쌍으로 되어 있기 때문에 남은 하나의 요소의 비트값만 남게됩니다.

3^3 = 0

5^5 = 0

3^5^3^5^7 = 7

Reference

 

OddOccurrencesInArray coding task - Learn to Code - Codility

Find value that occurs in odd number of elements.

app.codility.com