首页 > 其他 > 详细

[leetcode/lintcode 题解] 微软面试题:公平索引

时间:2020-07-21 12:40:46      阅读:98      评论:0      收藏:0      [点我收藏+]

现在给你两个长度均为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

[leetcode/lintcode 题解] 微软面试题:公平索引

原文:https://www.cnblogs.com/lintcode/p/13353557.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!