接上篇博文,第三个题目
A non-empty zero-indexed array A consisting of N positve integers is given. A pair of indices (P, Q), such that 0 <= P <= Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].
The equi-3 pair is a pair of indices (X, Y), such that 0 < X, X+1 < Y < N-1, and the sums of slices (0, X-1), (X+1, Y-1), (Y+1, N-1) are all equal.
That, given a non-empty zero-indexed array A consisting of N integers, returns 1 if array A contains an equi-3 pair and 0 otherwise.
Assume that:
N is an integer within the range [5..100,000];
each element of array A is an integer within the range [1..10,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
思考: 这个题目个人觉得最难的地方在时间复杂度是O(N), 因为要多次比较多个元素之和,嵌套循环似乎是避免不了的。后来看其他一些算法大神,学了个技巧,降低了复杂度。
public int solution(int[] A) {
int sum = 0, leftsum = 0, midsum = 0, rightsum = 0;
int n = A.length;
int[] sums = new int[n];
for (int i=0; i<n; i++) {
sum += A;
sums = sum;
}
int left = 1, right = n - 2;
while (left+1 < right) {
leftsum = sums[left-1];
midsum = sums[right-1] - sums[left];
rightsum = sums[n-1] - sums[right];
if ((leftsum == midsum) && (midsum == rightsum)) {
return 1;
} else if (leftsum > rightsum) {
right--;
} else if (leftsum < rightsum){
left++;
} else {
left++;
right--;
}
}
return 0;
}
转载于:https://blog.51cto.com/fushan/1673081