티스토리 뷰

알고리즘

[codility] 레슨2-2 OddOccurrencesInArray

Gibson 김형섭 2018. 3. 7. 22:31

A non-empty zero-indexed 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.

Assume that:

  • 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.

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.


문제해석


A = {9, 3, 9, 3, 9 ,7 ,9} 일 때 짝이 없는 정수를 찾아라.

return 7



이번에도 역시 처음에는 루프안에 루프를 돌려서 

각 인덱스에 있는 값이 일치하지 않은 값을 리턴하는 방법이 떠올랐다.


o(n)² 로 시간 복잡도가 좋지않다.


루프를 한번만 돌리면서 처음나온 숫자는 더해주고 중복이면 빼주는 방법이 좋겠다고 생각이 들어,

고민하다 비트연산을 떠올렸다.


XOR연산 (^) 으로 해결가능했다.


예를들어 A = {3, 5, 3}  이라면


3은 2진수로 변환 했을 때 0011

5는 0101 이 된다.


XOR연산을 하게되면 (보기편하게 세로로)    비트연산 설명 링크


0011

^

0101 = 0110


0110

^

0011 = 0101 이 된다.


0101은 5이므로 짝이 없는 수만 남았다.



제출한 코드.




class Solution { public int solution(int[] A) { int result = 0; for(int i : A){ result ^= i; } return result; } }





'알고리즘' 카테고리의 다른 글

[codility] 레슨2-1 CyclicRotation  (0) 2018.03.07
[codility] 레슨1 BinaryGap  (0) 2018.03.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
TAG
more
«   2024/05   »
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 31
글 보관함