Codewars/Java
[7kyu] 입력받은 배열에서 단일한 숫자를 반환 (Find the stray number)
pej4303
2019. 8. 3. 00:06
/**
* <pre>
* 입력받은 배열에서 단일한 숫자를 반환 (Find the stray number)
*
* 하나의 단일 숫자를 제외하고는 모두 동일한 홀수 길이의 정수 배열이 주어집니다.
* 그러한 배열을 받아들이는 메소드를 완성 해, 그 단일의 다른 번호를 돌려줍니다.
* 입력 배열은 항상 유효합니다! (홀수 길이> = 3)
*
* You are given an odd-length array of integers, in which all of them are the same, except for one single number.
* Complete the method which accepts such an array, and returns that single different number.
* The input array will always be valid! (odd-length >= 3)
* </pre>
*
* @param 정수형 배열
* @return 단일 숫자
* @author pej
* @date 2019. 03. 23.
* @example [1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3
*/
public static int stray(int[] numbers) {
HashSet<Integer> set = new HashSet<>(); // 중복된 데이터를 가지고 있는 HashSet
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] == numbers[j]) {
set.add(numbers[i]);
}
}
}
int result = 0;
for (int num : numbers) {
if (!set.contains(num)) {
result = num;
}
}
return result;
}