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& nums) {
        if(nums.size()<7){
            return false;
        }
        int len=nums.size();
        vectorpre_sum(len,0);
        //统计前缀和
        pre_sum[0]=nums[0];
        for(int i=1;i st;
            //统计前半段可能出现的分割值
            for(int i=1;i

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

上期推文:

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

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

LeetCode刷题实战542:01 矩阵

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

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

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

LeetCode刷题实战546:移除盒子

LeetCode刷题实战547:省份数量

LeetCode刷题实战548:将数组分割成和相等的子数组_第1张图片

你可能感兴趣的:(算法,leetcode,动态规划,面试,java)