Painless
OddOccurrencesInArray
Find the values that occur on odd elements.
Given a non-empty array A consisting of N integers. 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 unpaired element.
For example, in array A:
A [0] = 9 A [1] = 3 A [2] = 9
A [3] = 3 A [4] = 9 A [5] = 7
A [6] = 9
Write a function:
class Solution {public int solution(int [] A); }
Given an array A consisting of N integers that satisfy the above conditions, it returns the values of the unpaired elements.
For example, given the following array A:
A [0] = 9 A [1] = 3 A [2] = 9
A [3] = 3 A [4] = 9 A [5] = 7
A [6] = 9
As explained in the example above, the function should return 7.
Write an efficient algorithm for the following assumptions:
Detected time complexity:
O(N) or O(N*log(N))
Program OddOccurrencesInArray.java
OddOccurrencesInArray.java
public int solution(int[] A) {
int goal = 0;
java.util.Arrays.sort(A);
for (int i = 0; i < A.length -1; i++) {
if (A[i] != A[i + 1]) {
goal = A[i];
break;
}
i++;
}
if (goal == 0) {
goal = A[A.length - 1];
}
return goal;
}
jUnit OddOccurrencesInArrayTest.java
Report Candidate Report: training66EE8T-EUB
Recommended Posts