-
Notifications
You must be signed in to change notification settings - Fork 0
/
SingleNumber.java
53 lines (41 loc) · 1.11 KB
/
SingleNumber.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.leetcode.algorithms.easy.hashtable;
import java.util.Arrays;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class SingleNumber {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] nums = InputUtil.integerArr(inputs);
// Output
System.out.println(singleNumber(nums));
scanner.close();
}
public static int singleNumber(int[] nums) {
if(nums.length == 1) {
return nums[0];
}
Arrays.sort(nums);
int result = 0;
for(int i = 0; i < nums.length; i++) {
if(i == 0) {
if(nums[i] != nums[i + 1]) {
result = nums[i];
break;
}
} else if(i == nums.length - 1) {
if(nums[i] != nums[i - 1]) {
result = nums[i];
break;
}
} else {
if(nums[i] != nums[i - 1] && nums[i] != nums[i + 1]) {
result = nums[i];
break;
}
}
}
return result;
}
}