[codility/java] 2-2. OddOccurrencesInArray

jyleever·2022년 8월 12일
0

알고리즘

목록 보기
22/26

문제

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.

풀이

  • 1~N개의 홀수 개 원소로 이루어진 배열
  • 각 배열의 원소는 1~1,000,000,000
  • 각 원소가 짝을 이루는 가운데(같은 원소 값이 2개), 짝을 이루지 않은 원소를 찾아라

  • Map으로 풀이했더니 66%에서 멈췄다.
  • 인터넷을 찾아보니 XOR연산을 하다보면 같은 수는 0이 되고 다른 수는 1이 되면서 쭉쭉 가다가 결국 같은 수가 한 번 더 나오지 않은 수가 남는다고 한다.

코드

/**
XOR 연산 이용
- 같으면 0
- 다르면 1
**/

class Solution {
    public int solution(int[] A) {
        
        int answer = 0;
        for(int val : A){
            answer ^= val;
        }

        return answer;
    }
}

0개의 댓글