Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions:
- 0 < i, i + 1 < j, j + 1 < k < n - 1
- Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal.
where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R.
Example:
Input: [1,2,1,2,1,2,1] Output: True Explanation: i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1
Note:
- 1 <= n <= 2000.
- Elements in the given array will be in range [-1,000,000, 1,000,000].
思路:先固定j,然后左边分两半,sum相等就存入hashset,然后右边分两半,sum相等,就看sum在不在hashset里面;
这里presum用0开始的index,这样写prefixsum好写。严格按照// 0 < i, i + 1 < j, j + 1 < k < n - 1; 这个提示来写。
class Solution {
public boolean splitArray(int[] nums) {
if(nums == null || nums.length == 0) {
return false;
}
int n = nums.length;
int[] presum = new int[n];
presum[0] = nums[0];
for(int i = 1; i < n; i++) {
presum[i] = presum[i - 1] + nums[i];
}
//0 < i, i + 1 < j, j + 1 < k < n - 1
for(int j = 3; j < n - 3; j++) {
HashSet<Integer> set = new HashSet<>();
for(int i = 1; i + 1 < j; i++) {
if(presum[i - 1] == presum[j - 1] - presum[i]){
set.add(presum[i - 1]);
}
}
for(int k = j + 2; k < n - 1; k++) {
if(presum[n - 1] - presum[k] == presum[k - 1] - presum[j]) {
if(set.contains(presum[n - 1] - presum[k])) {
return true;
}
}
}
}
return false;
}
}