-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathSearchEquilibrium.java
47 lines (36 loc) · 1.02 KB
/
SearchEquilibrium.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
package exercise;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class SearchEquilibrium {
/*
TASK
주어진 배열에서 양 쪽의 합이 동일해지는 index의 값을 구한다.
*/
@Test
public void test() {
int[] arr = {-4, 8, 16, -22, 0, -4, 8, 16, -22};
assertThat(true, is(solution(arr) == 0 || solution(arr) == 4));
}
public int solution(int[] arr) {
if (arr == null) return -1;
double total = 0;
for (int i = 0; i < arr.length; i++) {
total += arr[i];
}
if (total - arr[0] == 0) {
return 0;
}
if (total - arr[arr.length - 1] == arr[arr.length - 1]) {
return arr.length - 1;
}
int left = 0;
for (int i = 1; i < arr.length; i++) {
left += arr[i - 1];
if ((total - arr[i])/2 == left) {
return i;
}
}
return -1;
}
}