티스토리 뷰
( https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ ) 문제링크.
If문으로 풀다가, 시간복잡도 측면에서도 그렇고, 이렇게 풀면 안될 것같았음. 따라서 다른사람의 풀이를 분석.
- XOR연산풀이.
public class OddOccurrencesInArray {
public static void main(String[] args) {
int[] arr = {9, 4, 9, 4, 7, 9, 9, 4, 4};
System.out.println(solution(arr));
}
public static int solution(int[] A) {
int answer = 0;
for(int num : A) {
answer ^= num; // answer = answer ^ num; a = a + 1 == a += 1;
}
return answer;
}
}
- 윗풀이 시간복잡도
O(N) or O(N*log(N))
* 필요개념
- What does for (int p : ps) do?
for (int p : ps)
counts[p]++;
-> This is a for-each loop(enhanced for). It sets p to the first element of ps, then runs the loop body. Then it sets p to the second element of ps, then runs the loop body. And so on.
- > ps자리에는 배열만 사용가능.
It's approximately short for:
for(int k = 0; k < ps.length; k++)
{
int p = ps[k];
counts[p]++;
}
- ^연산(XOR연산)
-> 양쪽 비트가 서로 다른 비트면 1, 아니면 0의 결과를 낸다. (10진수로 반환한다)
ex) 9(1001) ^ 15(1111) = 6(0110)
'Algorithm > Codility' 카테고리의 다른 글
Codility -6 TapeEquilibrium(Java) (0) | 2020.03.05 |
---|---|
Codility -5 PermMissingElem (0) | 2020.03.05 |
Codility -4 FrogJmp (0) | 2020.03.04 |
Codility -2 CyclicRotation(Java) (0) | 2020.03.04 |
Codility -1 Binary gap(Java) (0) | 2020.03.03 |
댓글
최근에 올라온 글
최근에 달린 댓글
TAG
- 20200421
- 20200512
- 20200624
- chapter8
- chapter7
- 생활코딩리눅스
- 20200403
- 20200502
- 20200429
- 20200423
- 20200424
- 20200427
- 20200413
- 20200510
- 20200428
- 20200317
- 20200622
- 20201204
- 20200420
- 20200415
- 20200804
- likelion
- 20200330
- 20200425
- 20200504
- 20200319
- 20200406
- 20200417
- 백준
- 20200503
- Total
- Today
- Yesterday