【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 Range Sum Query 2D - Immutable
- LintCode-K Sum
- LintCode-Subarray Sum
- [LintCode] 3Sum Smaller
- LintCode-Subarray Sum Closest
- LintCode-Minimum Path Sum
- LintCode-Kth Largest Element
- LeetCode-Range Sum Query - MutableLeetCode
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- LeetCode-Range Sum Query- ImmutableLeetCode
- LeetCode-Range Sum Query 2D - ImmutableLeetCode
- LeetCode-Range Sum Query 2D - MutableLeetCode
- take a risk
- Golang cannot take the address ofGolang
- sky-take-out chapter 1APT
- MLE 5217 : Take-Home Dataset Classification
- GCD SUMGC
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- Take-Two財報:2013Q1 Take-Two淨營收2.995億美元營收
- phpmysqlimysqli_query()mysqli_real_query()PHPMySql
- LINQ系列:LINQ to SQL Take/SkipSQL
- 'MessageBoxA' : function does not take 1 parameterFunction
- CSS選擇器筆記,element element和element > element 的區別CSS筆記
- leetcode15&16_3Sum&4SumLeetCode
- Query sqlSQL
- Query DSL
- reg query /?
- Laravel 中 offset,limit 或 skip , take 的使用LaravelMIT
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- mysql 配置 General Query Log和# Slow Query LogMySql
- SQL groupby sum 用法SQL
- Split Array Largest Sum
- Pairwise Sum and DivideAIIDE
- oracle 字串 聚合 sumOracle字串
- Missing Subsequence Sum