算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: