Skip to content

Commit f6f2f76

Browse files
committed
isse #29 Lonely Integer java w/ Explanation
1 parent e907c20 commit f6f2f76

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package hackerrank;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class LonelyInteger {
8+
9+
static int lonelyinteger(int[] a) {
10+
// ๋ฐ˜๋ณต๋˜์ง€ ์•Š๋Š” ์š”์†Œ ์ฐพ์•„์„œ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ
11+
12+
//sol1 -> Time limit exceeded
13+
/*
14+
if(a.length == 1) return a[0];
15+
16+
//๋ฐฐ์—ด a ์ •๋ ฌํ•˜๊ธฐ
17+
Arrays.sort(a);
18+
19+
//๋ฐฐ์—ด a๋ฅผ ๋ฆฌ์ŠคํŠธ์— ๋‹ด๊ธฐ
20+
List<Integer> alist = new ArrayList<>(a.length);
21+
22+
for(int i : a){
23+
alist.add(i);
24+
}
25+
26+
//์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ์—์„œ i๋ฒˆ์งธ์™€ i+1๋ฒˆ์งธ๊ฐ€ ๊ฐ™์œผ๋ฉด ๋‘˜ ๋‹ค ๋ฆฌ์ŠคํŠธ์—์„œ ์ œ๊ฑฐ.
27+
int i=0;
28+
while(alist.size() != 1){
29+
if(alist.get(i) == alist.get(i+1)){
30+
alist.remove(i);
31+
alist.remove(i);
32+
}
33+
}
34+
35+
//๋ฆฌํ„ดํƒ€์ž…์ด int๋‹ˆ๊นŒ 0๋ฒˆ์งธ ์ถœ๋ ฅ
36+
return alist.get(0);
37+
*/
38+
39+
//sol2
40+
if (a.length == 1) {
41+
return a[0];
42+
}
43+
44+
//๋ฐฐ์—ด a ์ •๋ ฌํ•˜๊ธฐ
45+
Arrays.sort(a);
46+
47+
int ans = 0;
48+
for (int i = 1; i < a.length; i++) {
49+
//์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ํ–ˆ๊ธฐ๋•Œ๋ฌธ์— ์•ž์˜ ๋ชจ๋“  ์ˆซ์ž๊ฐ€ 2๊ฐœ์”ฉ ์กด์žฌํ•œ๋‹ค๋ฉด ๋‹ต์€ ์ œ์ผ ๋งˆ์ง€๋ง‰ ์š”์†Œ์ด๋‹ค.
50+
if (i == a.length - 1) {
51+
ans = a[i];
52+
//์˜ค๋ฅธ์ฐจ์ˆœ ์ •๋ ฌ์„ ํ–ˆ๊ธฐ๋•Œ๋ฌธ์— ํ˜„์žฌ์š”์†Œ์˜ ์™ผ์ชฝ ์š”์†Œ์™€ ์˜ค๋ฅธ์ชฝ ์š”์†Œ๊ฐ€ ํ˜„์žฌ์š”์†Œ์™€ ๋‹ค๋ฅด๋‹ค๋ฉด ๊ทธ ๊ฐ’์ด ๋‹ต์ด๋‹ค.
53+
} else if ((a[i] != a[i - 1]) && (a[i] != a[i + 1])) {
54+
ans = a[i];
55+
break;
56+
}
57+
}
58+
return ans;
59+
}
60+
61+
public static void main(String[] args) {
62+
System.out.println(lonelyinteger(new int[]{1,2,3,4,3,2,1})+", ans: 4");
63+
// System.out.println(lonelyinteger(new int[]{1})+", ans: 1");
64+
// System.out.println(lonelyinteger(new int[]{1,1,2})+", ans: 2");
65+
// System.out.println(lonelyinteger(new int[]{0, 0, 1, 2, 1}) + ", ans: 2");
66+
// System.out.println(lonelyinteger(
67+
// new int[]{59, 88, 14, 8, 85, 1, 94, 74, 57, 96, 39, 2, 47, 43, 35, 17, 53, 52, 92, 31,
68+
// 99, 48, 94, 30, 92, 60, 32, 45, 88, 13, 39, 50, 22, 65, 89, 46, 65, 76, 57, 67, 99, 35,
69+
// 76, 46, 85, 82, 45, 62, 53, 80, 74, 22,
70+
// 31, 52, 82, 13, 41, 96, 2, 1, 80, 62, 4, 20, 50, 89, 59, 67, 60, 8, 41, 14, 47, 48, 17,
71+
// 4, 43, 30, 32}) + ", ans: 20");
72+
}
73+
}

0 commit comments

Comments
ย (0)