【Lintcode】1559. Take the Element and Query the Sum
題目地址:
https://www.lintcode.com/problem/take-the-element-and-query-the-sum/description
給定一個長 n n n的陣列 A A A,求 ∑ 0 ≤ i < j < n A [ i ] A [ j ] \sum_{0\le i<j<n}A[i]A[j] ∑0≤i<j<nA[i]A[j]。
思路是字首和陣列。可以這樣看: ∑ 0 ≤ i < j < n A [ i ] A [ j ] = ∑ j = 1 n − 1 ( A [ j ] ∑ i = 0 j − 1 A [ i ] ) \sum_{0\le i<j<n}A[i]A[j]=\sum_{j=1}^{n-1}(A[j]\sum_{i=0}^{j-1}A[i]) 0≤i<j<n∑A[i]A[j]=j=1∑n−1(A[j]i=0∑j−1A[i])程式碼如下:
public class Solution {
/**
* @param arr: the arr
* @return: the sum
*/
public int takeTheElementAndQueryTheSum(int[] arr) {
// Write your code here
long[] preSum = new long[arr.length + 1];
long res = 0, MOD = (long) (1E9 + 7);
for (int i = 0; i < arr.length; i++) {
preSum[i + 1] = preSum[i] + arr[i];
preSum[i + 1] %= MOD;
}
for (int i = arr.length - 1; i >= 0; i--) {
res += arr[i] * preSum[i] % MOD;
res %= MOD;
}
return (int) res;
}
}
時空複雜度 O ( n ) O(n) O(n)。
相關文章
- [LintCode] 3Sum Smaller
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- take a risk
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- GCD SUMGC
- Sum Problem
- 集合sum
- sky-take-out chapter 1APT
- 15+18、3Sum 4Sum
- reg query /?
- Query DSL
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- ES 筆記十:Query String & Simple Query String筆記
- MLE 5217 : Take-Home Dataset Classification
- leetcode Sum系列LeetCode
- Sum of Left Leaves
- Path-sum
- Path Sum III
- Leetcode Path SumLeetCode
- B - Minimum Sum
- Range Minimum Sum
- Missing Subsequence Sum
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers