【Lintcode】1793. Balanced Sales Array
題目地址:
https://www.lintcode.com/problem/balanced-sales-array/description
給定一個陣列 A A A,求某個下標 k k k使得 ∑ i = 1 k − 1 A [ i ] = ∑ i = k + 1 l A − 1 A [ i ] \sum_{i=1}^{k-1}A[i]=\sum_{i=k+1}^{l_A-1}A[i] i=1∑k−1A[i]=i=k+1∑lA−1A[i]題目保證解存在。
思路是字首和,可以降低時間複雜度。程式碼如下:
public class Solution {
/**
* @param sales: a integer array
* @return: return a Integer
*/
public int BalancedSalesArray(int[] sales) {
// write your code here
int[] preSum = new int[sales.length + 1];
for (int i = 0; i < sales.length; i++) {
preSum[i + 1] = preSum[i] + sales[i];
}
for (int i = 0; i < sales.length; i++) {
if (preSum[i] == preSum[sales.length] - preSum[i + 1]) {
return i;
}
}
return -1;
}
}
時空複雜度 O ( l A ) O(l_A) O(lA)。
相關文章
- 【Lintcode】576. Split Array
- 【Lintcode】1623. Minimal Distance In The Array
- Balanced Subsequences
- 110-Balanced Binary Tree
- SAP Cloud for Customer裡Sales Order和Sales Quote的建模方式Cloud
- POJ3264 Balanced Lineup【RMQ】MQ
- CF1237H Balanced Reversals
- POJ 3264 Balanced Lineup【RMQ問題】MQ
- HDU 6299-Balanced Sequence(貪心)
- [題解]SP10606 Balanced Numbers
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- How to get propose products in Sales Order
- SAP CRM Fiori應用如何啟用Sales Office和Sales Group兩個欄位
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- Array.from和 Array.of
- array
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- Array()與Array.of()方法區別
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- 淺談SAP Cloud for Sales 自動化Cloud
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【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】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie