1
This commit is contained in:
+47
-23
@@ -49,39 +49,63 @@ class Solution {
|
|||||||
|
|
||||||
|
|
||||||
public static boolean canThreePartsEqualSum(int[] arr) {
|
public static boolean canThreePartsEqualSum(int[] arr) {
|
||||||
int sum = Arrays.stream(arr).sum();
|
int sum = 0;
|
||||||
|
for (int a : arr) {
|
||||||
|
sum += a;
|
||||||
|
}
|
||||||
if (sum % 3 != 0) {
|
if (sum % 3 != 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
int avg = sum / 3;
|
int avg = sum / 3;
|
||||||
for (int i = 0; i < arr.length; i++) {
|
sum = avg;
|
||||||
int tmp = avg - arr[i];
|
int res = 0;
|
||||||
if (tmp > 0) {
|
int j = 0;
|
||||||
} else if (tmp == 0) {
|
while (j < arr.length - 1 && res < 2) {
|
||||||
|
sum -= arr[j];
|
||||||
for (int j = i + 1; j < arr.length; j++) {
|
if (sum == 0) {
|
||||||
tmp = avg - arr[i + 1];
|
res++;
|
||||||
tmp = tmp - arr[j];
|
sum = avg;
|
||||||
if (tmp > 0) {
|
|
||||||
|
|
||||||
}
|
|
||||||
if (tmp == 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (tmp < 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (res == 2) {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static boolean canThreePartsEqualSum2(int[] arr) {
|
||||||
|
int sum = 0;
|
||||||
|
for (int a : arr) {
|
||||||
|
sum += a;
|
||||||
|
}
|
||||||
|
if (sum % 3 != 0) return false;
|
||||||
|
int target = sum / 3;
|
||||||
|
sum = 0;
|
||||||
|
int i = 0;
|
||||||
|
while (i < arr.length) {
|
||||||
|
sum += arr[i];
|
||||||
|
if (sum == target) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (sum != target) return false;
|
||||||
|
int j = i + 1;
|
||||||
|
while (j < arr.length - 1) {
|
||||||
|
sum += arr[j];
|
||||||
|
if (sum == 2 * target) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
int[] a = new int[]{3, 3, 6, 5, -2, 2, 5, 1, -9, 4};
|
int[] a = new int[]{1, -1, 1, -1};
|
||||||
System.out.println(canThreePartsEqualSum(a));
|
System.out.println(canThreePartsEqualSum(a));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user