개발하는 두더지

[Kodility] OddOccurrencesInArray 본문

알고리즘

[Kodility] OddOccurrencesInArray

덜지 2019. 1. 30. 15:24

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.
Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.




HashSet<Integer> valueSet = new HashSet<>();
for(int v : A) {
if(!valueSet.contains(v)) {
valueSet.add(v);
continue;
}

valueSet.remove(v);
}

Iterator iterator = valueSet.iterator();
return (int)iterator.next();


중복으로 값을 저장할 수 없는 Set을 이용

문제에서보면 1개의 값을 빼곤 전부 짝을 이룬다고 했으니 짝이되는 값들을 지우면 한개의 값이 나온다. 그값을 리턴.


하지만 이 식의 시간복잡도는 


O(N) or O(N*log(N))








인터넷 검색결과 엄청 쉽게 푸는 방법이 있었다


int result = 0;
for(int v : A) {
result = result ^ v;
}
return result;


XOR 연산을 이용하여 푸는 방법이다.


a : 1011

b : 1101

----------

c : 0110


같으면 0 다르면 1







Comments