Split Array with Equal Sum 简化版

http://www.1point3acres.com/bbs/thread-319358-1-1.html

如果只有非负数,可以同向双指针

    public boolean splitArray(int[] nums) {
        int n = nums.length;
        int l = 0, r = n - 1;
        int sumL = nums[0], sumR = nums[n - 1];
        while (l < r) {
            if (sumL < sumR) {
                l++;
                sumL += nums[l];
            } else {
                r--;
                sumL += nums[r];
            }
        }
        return sumL == sumR;
    }

如果有负数

遍历一边,找到sum,然后看sum % 2 == 1,成立,说明无法分割,不成立,说明有可能分割。然后再遍历一边,前缀和等于(sum / 2)即可

results matching ""

    No results matching ""