-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathLonelyInteger.java
More file actions
73 lines (60 loc) ยท 2.2 KB
/
LonelyInteger.java
File metadata and controls
73 lines (60 loc) ยท 2.2 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package hackerrank;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LonelyInteger {
static int lonelyinteger(int[] a) {
// ๋ฐ๋ณต๋์ง ์๋ ์์ ์ฐพ์์ ์ถ๋ ฅํ๋ ๋ฌธ์
//sol1 -> Time limit exceeded
/*
if(a.length == 1) return a[0];
//๋ฐฐ์ด a ์ ๋ ฌํ๊ธฐ
Arrays.sort(a);
//๋ฐฐ์ด a๋ฅผ ๋ฆฌ์คํธ์ ๋ด๊ธฐ
List<Integer> alist = new ArrayList<>(a.length);
for(int i : a){
alist.add(i);
}
//์ค๋ฆ์ฐจ์ ์ ๋ ฌ๋ ๋ฆฌ์คํธ์์ i๋ฒ์งธ์ i+1๋ฒ์งธ๊ฐ ๊ฐ์ผ๋ฉด ๋ ๋ค ๋ฆฌ์คํธ์์ ์ ๊ฑฐ.
int i=0;
while(alist.size() != 1){
if(alist.get(i) == alist.get(i+1)){
alist.remove(i);
alist.remove(i);
}
}
//๋ฆฌํดํ์
์ด int๋๊น 0๋ฒ์งธ ์ถ๋ ฅ
return alist.get(0);
*/
//sol2
if (a.length == 1) {
return a[0];
}
//๋ฐฐ์ด a ์ ๋ ฌํ๊ธฐ
Arrays.sort(a);
int ans = 0;
for (int i = 1; i < a.length; i++) {
//์ค๋ฆ์ฐจ์ ์ ๋ ฌ์ ํ๊ธฐ๋๋ฌธ์ ์์ ๋ชจ๋ ์ซ์๊ฐ 2๊ฐ์ฉ ์กด์ฌํ๋ค๋ฉด ๋ต์ ์ ์ผ ๋ง์ง๋ง ์์์ด๋ค.
if (i == a.length - 1) {
ans = a[i];
//์ค๋ฅธ์ฐจ์ ์ ๋ ฌ์ ํ๊ธฐ๋๋ฌธ์ ํ์ฌ์์์ ์ผ์ชฝ ์์์ ์ค๋ฅธ์ชฝ ์์๊ฐ ํ์ฌ์์์ ๋ค๋ฅด๋ค๋ฉด ๊ทธ ๊ฐ์ด ๋ต์ด๋ค.
} else if ((a[i] != a[i - 1]) && (a[i] != a[i + 1])) {
ans = a[i];
break;
}
}
return ans;
}
public static void main(String[] args) {
System.out.println(lonelyinteger(new int[]{1,2,3,4,3,2,1})+", ans: 4");
// System.out.println(lonelyinteger(new int[]{1})+", ans: 1");
// System.out.println(lonelyinteger(new int[]{1,1,2})+", ans: 2");
// System.out.println(lonelyinteger(new int[]{0, 0, 1, 2, 1}) + ", ans: 2");
// System.out.println(lonelyinteger(
// new int[]{59, 88, 14, 8, 85, 1, 94, 74, 57, 96, 39, 2, 47, 43, 35, 17, 53, 52, 92, 31,
// 99, 48, 94, 30, 92, 60, 32, 45, 88, 13, 39, 50, 22, 65, 89, 46, 65, 76, 57, 67, 99, 35,
// 76, 46, 85, 82, 45, 62, 53, 80, 74, 22,
// 31, 52, 82, 13, 41, 96, 2, 1, 80, 62, 4, 20, 50, 89, 59, 67, 60, 8, 41, 14, 47, 48, 17,
// 4, 43, 30, 32}) + ", ans: 20");
}
}