반응형
1. 문제
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:
int solution(vector<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.
주어진 vector A에서, 쌍이 되지 않는 요소를 찾는 문제.
2. 풀이 전략
vector 요소를 map에 key로 저장한다.
이 후, value 값이 홀수인 요소를 찾는다.
3. 코드 (C++)
#include <map>
int solution(vector<int> &A) {
map<int, int> m = {};
//vector A의 요소를 key로 하는 map 생성
for(size_t i = 0; i < A.size(); i++)
{
auto it = m.find(A[i]); //A요소가 map에 있는지 찾는다.
if(it == m.end()) m.insert(pair<int, int>(A[i], 1)); // 없으면 추가
else it->second += 1; // 있으면 value 증가
}
//value 값이 홀수인 요소 찾기
for(const auto& pair : m)
{
if(pair.second % 2 != 0) return pair.first;
}
return 0;
}
4. 결과

반응형
'Algorithm Problem > Codility' 카테고리의 다른 글
| Lesson 3. Time Complexity - PermMissingElem (0) | 2024.09.28 |
|---|---|
| Lesson 3. Time Complexity - FrogJmp (0) | 2024.09.28 |
| Lesson 2. Arrays - OddOccurrencesInArray #2 (속도 개선) (0) | 2024.09.25 |
| Lesson 2. Arrays - CyclicRotation (0) | 2024.09.21 |
| Lesson 1. Iterations - BinaryGap (0) | 2024.09.18 |