1. 程式人生 > 實用技巧 >[leetcode/lintcode 題解] 微軟面試題:公平索引

[leetcode/lintcode 題解] 微軟面試題:公平索引

現在給你兩個長度均為N的整數陣列 A 和 B。

當(A[0]+...A[K-1]),(A[K]+...+A[N-1]),(B[0]+...+B[K-1]) 和 (B[K]+...+B[N-1])四個和值大小相等時,稱索引K是一個公平索引。也就是說,索引K 可以使得A, B 兩個陣列被分成兩個非空陣列,這四個子陣列的和值相等。

例如,陣列A = [4,-1,0,3],B = [-2,5,0,3],那麼索引 K = 2是公平的,子陣列的和相等:4+(-1) = 3; 0+3 = 3; -2 + 5 = 3 and 0 + 3 = 3。

現在請你計算公平索引的個數。

  • 2<=N<=100000
  • -1000000000<=a[i],b[i]<=1000000000 (0<=i<N)

線上評測地址:https://www.lintcode.com/problem/fair-indexes/?utm_source=sc-bky-zq

樣例 1:

輸入: [4,-1,0,3] [-2,5,0,3]
輸出: 2

樣例 2:

輸入: [2,-2,-3,3]
[0,0,4,-4]
輸出: 1

樣例 3:

輸入: [4,-1,0,3] [-2,6,0,4]
輸出: 0

樣例 4:

輸入: [1,4,2,-2,5] [7,-2,-2,2,5]
輸出: 2

【題解】

先判斷兩個陣列總和是否相等,若不相等,則直接返回0; 然後掃一遍陣列,用pre_a和pre_b分別記錄兩個陣列的字首和,字首和相等時ans++即可。 需要注意的是,陣列中數的值在-1e9,1e9範圍內,陣列長度0,1e5,所以中間和會超出int範圍,需要用long; 還有被分成的兩個陣列不能為空,所以字首和p0和pn-1是不考慮的;

public class Solution {
    /**
     * @param A: an array of integers
     * @param B: an array of integers
     * @return: return a integer indicating the number of fair indexes.
     */
    public int CountIndexes(List<Integer> A, List<Integer> B) {
        int ans = 0;
        long sum_a = 0
, sum_b = 0, pre_a = 0, pre_b = 0; for(int i = 0; i < A.size(); i++) { sum_a += A.get(i); sum_b += B.get(i); } if(sum_a != sum_b)return 0; for(int i = 0; i < A.size() - 1; i++) { pre_a += A.get(i); pre_b += B.get(i); if(pre_a==pre_b) ans++; } return ans; } }

更多語言程式碼參見:https://www.jiuzhang.com/solution/fair-indexes/?utm_source=sc-bky-zq