【Lintcode】1793. Balanced Sales Array

記錄演算法發表於2020-12-03

題目地址:

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=1k1A[i]=i=k+1lA1A[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)

相關文章