LeetCode #548 - Split Array with Equal Sum

题目描述:

Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions:

1. 0 < i, i + 1 < j, j + 1 < k < n - 1

2. Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal.

where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R.

Example:

Input: [1,2,1,2,1,2,1]

Output: True

Explanation:

i = 1, j = 3, k = 5. 

sum(0, i - 1) = sum(0, 0) = 1

sum(i + 1, j - 1) = sum(2, 2) = 1

sum(j + 1, k - 1) = sum(4, 4) = 1

sum(k + 1, n - 1) = sum(6, 6) = 1

Note:

1. 1 <= n <= 2000.

2. Elements in the given array will be in range [-1,000,000, 1,000,000].

从数组中找三个元素,将这三个元素删除,拆分得到四个子数组,保证每个子数组和相等。利用前缀和可以在O(1)的时间复杂度求得一段子数组和,如果枚举i,j,k三个下标,时间复杂度是O(n^3),更好的方法是先枚举j,然后分别对i和k枚举,时间复杂度是O(n^2)。

class Solution {
public:
    bool splitArray(vector<int>& nums) {
        int n=nums.size();
        if(n<7) return false;
        vector<int> prefix_sum(n,0);
        prefix_sum[0]=nums[0];
        for(int i=1;i<n;i++) prefix_sum[i]=prefix_sum[i-1]+nums[i];
        for(int j=3;j<n-3;j++)
        {
            unordered_map<int,bool> hash;
            for(int i=1;i<j-1;i++)
            {
                int a=prefix_sum[i-1];
                int b=prefix_sum[j-1]-prefix_sum[i];
                if(a==b) hash[a]=true;
            }
            for(int k=j+2;k<n-1;k++)
            {
                int c=prefix_sum[k-1]-prefix_sum[j];
                int d=prefix_sum[n-1]-prefix_sum[k];
                if(c==d&&hash.count(c)>0) return true;
            }
        }
        return false;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值