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.
private fun solution(A: IntArray): Int {
// !! time complexity O(N**2) !!
// return A.mapIndexed { index, i -> i to index }
// .groupBy { it.first }
// .filterValues { it.size < 2 }
// .keys.first()
// !! time complexity O(N**2) !!
// val nums = A.toList()
// return nums.filter { item -> nums.count{ it == item} == 1}[0]
/** time complex O(N) or O(N*log(N)) */
var result = 0
A.forEach {
//xor 숫자가 같으면 0 다르면 1
result = result xor it
}
return result
}
답지 보고 푼 케이스
시간 복잡도 O(N) or O(N*log(N))
xor이 binary로 바꾸게되면 서로 달랐을때만 true를 리턴해주기 때문에
result를 0으로 시작했을때, 같은값이 두번 들어오면 다시 0이 됨.
고로 중복이 제거되어 한번만 나오는 값이 리턴되는 형식.
'코딩테스트 > codility' 카테고리의 다른 글
[codillity] kotlin - lesson3. TapeEquilibrium (0) | 2022.10.30 |
---|---|
[codillity] kotlin - lesson3. PermMissingElem (0) | 2022.10.30 |
[codillity] kotlin - lesson3. FrogImp (0) | 2022.10.30 |
[codillity] kotlin - lesson2. cyclicRotation (0) | 2022.10.30 |
[codillity] kotlin - Lesson1. BinaryGap (0) | 2022.10.30 |