Given a 0-indexed integer array nums
, find a 0-indexed integer array answer
where:
answer.length == nums.length
.answer[i] = |leftSum[i] - rightSum[i]|
.
Where:
leftSum[i]
is the sum of elements to the left of the indexi
in the arraynums
. If there is no such element,leftSum[i] = 0
.rightSum[i]
is the sum of elements to the right of the indexi
in the arraynums
. If there is no such element,rightSum[i] = 0
.
Return the array answer
.
Example 1:
Input: nums = [10,4,8,3] Output: [15,1,11,22] Explanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].
Example 2:
Input: nums = [1] Output: [0] Explanation: The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0].
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 105
这题定义了leftSum为从左到右的prefix sum,rightSum为从右到左的prefix sum,求每个下标对应的Math.abs(leftSum - rightSum)。
最直观的做法就是用两个数组两个for loop分别求两边的prefix sum,然后再一个for loop做减法。
class Solution {
public int[] leftRightDifference(int[] nums) {
int len = nums.length;
int[] leftSum = new int[len];
int[] rightSum = new int[len];
for (int i = 0; i < len; i++) {
leftSum[i] = (i == 0) ? nums[i] : leftSum[i - 1] + nums[i];
}
for (int i = len - 1; i >= 0; i--) {
rightSum[i] = (i == len - 1) ? nums[i] : rightSum[i + 1] + nums[i];
}
int[] result = new int[len];
for (int i = 0; i < len; i++) {
result[i] = Math.abs(leftSum[i] - rightSum[i]);
}
return result;
}
}
然后看到有更简洁的方法,不需要额外的leftSum和rightSum数组就可以了。思路是先求出整个数组的sum。然后再从左往右for loop,sum - nums[i]其实就是rightSum[i](每次需要更新sum),此时再动态求leftSum就可以了。
class Solution {
public int[] leftRightDifference(int[] nums) {
int len = nums.length;
int sum = 0;
for (int i = 0; i < len; i++) {
sum += nums[i];
}
int[] result = new int[len];
int leftSum = 0;
for (int i = 0; i < len; i++) {
int curr = nums[i];
sum -= nums[i];
result[i] = Math.abs(leftSum - sum);
leftSum += nums[i];
}
return result;
}
}