【Leetcode】1685. Sum of Absolute Differences in a Sorted Array
阿新 • • 發佈:2020-12-15
技術標籤:# 棧、佇列、串及其他資料結構leetcode演算法
題目地址:
https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/
給定一個長 n n n的非降陣列 A A A,要求返回一個數組 B B B,使得 B [ i ] = ∑ j = 0 n − 1 ∣ A [ i ] − A [ j ] ∣ B[i]=\sum_{j=0}^{n-1}|A[i]-A[j]| B[i]=j=0∑n−1∣A[i]−A[j]∣
思路是字首和。求出字首和陣列
p
p
p使得
p
[
0
]
=
0
,
∀
i
>
0
,
p
[
i
]
=
∑
j
=
0
i
−
1
A
[
j
]
p[0]=0,\forall i>0,p[i]=\sum_{j=0}^{i-1}A[j]
p[0]=0,∀i>0,p[i]=∑j=0i−1A[j]。則
B
[
i
]
=
(
i
A
[
i
]
−
p
[
i
]
)
+
(
p
[
n
]
−
p
[
i
+
1
]
−
(
n
−
1
−
i
)
A
[
i
]
)
=
(
2
i
+
1
−
n
)
A
[
i
]
−
p
[
i
]
−
p
[
i
+
1
]
+
p
[
n
]
B[i]=(iA[i]-p[i])+(p[n]-p[i+1]-(n-1-i)A[i])\\=(2i+1-n)A[i]-p[i]-p[i+1]+p[n]
B[i]=(iA[i]−p[i])+(p[n]−p[i+1]−(n−1−i)A[i])=( 2i+1−n)A[i]−p[i]−p[i+1]+p[n]程式碼如下:
public class Solution {
public int[] getSumAbsoluteDifferences(int[] nums) {
int n = nums.length;
int[] preSum = new int[n + 1];
for (int i = 0; i < n; i++) {
preSum[i + 1] = preSum[i] + nums[i];
}
for (int i = 0; i < n; i++) {
nums[i] = (2 * i + 1 - n) * nums[i] - preSum[i] + preSum[n] - preSum[i + 1];
}
return nums;
}
}
時空複雜度 O ( n ) O(n) O(n)。