[leetcode/lintcode 題解] 微軟面試題:公平索引
阿新 • • 發佈:2020-07-21
輸入: [4,-1,0,3] [-2,5,0,3] 輸出: 2
輸入: [2,-2,-3,3] [0,0,4,-4] 輸出: 1
輸入: [4,-1,0,3] [-2,6,0,4] 輸出: 0
輸入: [1,4,2,-2,5] [7,-2,-2,2,5] 輸出: 2
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; } }