​LeetCode刷题实战548:将数组分割成和相等的子数组

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 将数组分割成和相等的子数组,我们先来看题面:

https://leetcode-cn.com/problems/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:

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

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.

给定一个有 n 个整数的数组,你需要找到满足以下条件的三元组 (i, j, k) :

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

子数组 (0, i - 1),(i + 1, j - 1),(j + 1, k - 1),(k + 1, n - 1) 的和应该相等。

这里我们定义子数组 (L, R) 表示原数组从索引为L的元素开始至索引为R的元素。

示例                         

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

解题

https://blog.csdn.net/weixin_44171872/article/details/108986194

主要思路:

(1)先确定 j 的位置,然后再在前后两端进行判断是否存在 i 和 k ;

(2)先在前半段确定可能的 i ,既 i 将前半段分成相等的两份,并使用unordered_set 统计此时的值;

(3)再在后半段确定 k ,此时的 k 要满足能够将后半段分成相等的两份,且此时的值在前半段的unordered _set 中出现过,返回true;

(4)跳出循环,说明没有找到满足要求的 i j k,故返回false;

class Solution {
public:
    bool splitArray(vector<int>& nums) {
        if(nums.size()<7){
            return false;
        }
        int len=nums.size();
        vector<int>pre_sum(len,0);
        //统计前缀和
        pre_sum[0]=nums[0];
        for(int i=1;i<len;++i){
            pre_sum[i]=pre_sum[i-1]+nums[i];
        }
        //使用 j 进行分割
        for(int j=3;j<len-3;++j){
            unordered_set<int> st;
            //统计前半段可能出现的分割值
            for(int i=1;i<j-1;++i){
                if(pre_sum[i-1]==pre_sum[j-1]-pre_sum[i]){
                    st.insert(pre_sum[i-1]);
                }
            }
            //判断后半段是否能够出现满足要求的 k
            for(int k=j+2;k<len-1;++k){
                if(pre_sum[k-1]-pre_sum[j]==pre_sum[len-1]-pre_sum[k]&&st.count(pre_sum[k-1]-pre_sum[j])){
                    return true;
                }
            }
        }
        //跳出循环,返回false
        return false;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-540题汇总,希望对你有点帮助!

LeetCode刷题实战541:反转字符串 II

LeetCode刷题实战542:01 矩阵

LeetCode刷题实战543:二叉树的直径

LeetCode刷题实战544:输出比赛匹配对

LeetCode刷题实战545:二叉树的边界

LeetCode刷题实战546:移除盒子

LeetCode刷题实战547:省份数量

54a643b7d4014b69080be12e61a94e4b.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值