| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
- Codility
- 반응형웹
- 파이썬
- 반응형 웹 프로젝트
- rnn
- html 프로젝트
- 상속
- FFT
- inline
- Database
- oracle
- HTML
- 예제
- CSS
- g검정
- FileWriter
- FlowLayout
- html 기초
- java
- 사전학습
- 퍼셉트론
- 메서드
- 푸리에 변환
- GridLayout
- 미디어쿼리
- Position
- iframe 태그
- ObjectOutputStream
- BorderLayout
- css 기초
- Today
- Total
도라에몽주머니
[Codility/Java] 문제 3. OddOccurrencesInArray 본문

Task
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
class Solution {
public int solution(int[] A) {
int result = 0;
for(int i=0; i<A.length; i++) {
result = result ^ A[i];
}
return result;
}
}
Notion
XOR 비트연산(^)
: 대응되는 비트가 서로 다른 경우, 1을 반환함.
즉, 이번 문제에서 같은 숫자를 xor 연산하게 되면 모두 0000의 비트를 반환하게 되고, 이를 마지막 남은 짝이 없는 숫자와 xor 연산을 하면 결국 남은 숫자가 return 되게 된다.
사실 이 문제는 답을 떠올리지 못해서 해설을 검색해서 풀었다.
HashMap을 활용해 푼 사람들도 있었는데 시간복잡도면에서 가장 효율이 좋은 xor 알고리즘으로 풀어보았다. 답을 보면서도 이런 생각을 문제를 보자마자 어떻게 떠올렸을까 싶었다.
연습만이 살길! 열심히 해보자.
'Algorithm' 카테고리의 다른 글
| [Codility/Java] 문제 6. TapeEquilibrium (0) | 2022.12.06 |
|---|---|
| [Codility/Java] 문제 5. PermMissingElem (0) | 2022.11.24 |
| [Codility/Java] 문제 4. FrogJmp (0) | 2022.11.22 |
| [Codility/Java] 문제 2. CyclicRotation (0) | 2022.11.17 |
| [Codility/Java] 문제 1. BinaryGap (0) | 2022.11.04 |