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:
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] = 9the 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.
import java.util.Set;
import java.util.HashSet;
class Solution {
public int solution(int[] A) {
Set<Integer> set = new HashSet<>();
for(int num : A) {
if(set.contains(num)) {
set.remove(num);
}else {
set.add(num);
}
}
return set.iterator().next();
}
}
1. 풀이 전략
1) 짝을 이루지 않는 수(1개만 있는)를 리턴해야 한다.
2) A의 원소 값을 가지는 새로운 배열을 만들고, A의 값이 새로운 배열의 인덱스가 될 수 있는지 판단한다.
3) 문제에서 A의 값이 될 수 있는 원소는 10억까지로 매우 크기 때문에, 2)의 방법은 옳지않다.
4) Java에서 중복값을 허용하지 않는 Set Collection을 사용하여 문제를 해결한다.
5) set을 instance화 하여, A 배열에 담겨있는 값을 하나씩 저장한다. 그러나, 이미 포함되어 있으면 제거한다.
6) 결국 set에는 짝을 이루지 않는 단 하나의 요소만 저장이 된다.
(set.contains(value)에 걸렸던 값은 set에서 아예 제거되므로)
7) set.iterator().next()를 통해 단 하나의 짝을 이루지 않는 값을 리턴한다.
출처 : Codility (https://app.codility.com/programmers)
'코딩 테스트 > Codility' 카테고리의 다른 글
Codility - FlogJmp (0) | 2023.03.26 |
---|---|
Codility - CyclicRotation (0) | 2023.03.26 |
Codility - BinaryGap (0) | 2023.03.25 |