zoukankan      html  css  js  c++  java
  • 【LeetCode Weekly Contest 26 Q4】Split Array with Equal Sum

    【题目链接】:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/split-array-with-equal-sum/

    【题意】

    让你把一段序列去掉3个元素,然后分成4个部分;
    要求这4个部分的和相同;
    问你可不可能;

    【题解】

    先枚举要删除的3个元素中的中间那个元素j;
    然后把整个序列分成左边和右边两个部分;
    然后再左边的序列中枚举i;
    然后把0..j-1分成0..i-1和i+1..j-1两个部分;
    然后看这两个部分各自的和是不是相同;
    相同的话把和用map记录一下;
    然后再枚举
    右半部分即第3个元素k;
    分成
    j+1..k-1和k+1..n-1两个部分;
    看看各自的和是不是相同;
    相同的话,看看刚才左半部分记录的map里面有没有这个和;
    有的话输出true
    复杂度接近O(n^2)吧->用了map哦。

    【完整代码】

    #include <bits/stdc++.h>
    using namespace std;
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    #define LL long long
    #define rep1(i,a,b) for (int i = a;i <= b;i++)
    #define rep2(i,a,b) for (int i = a;i >= b;i--)
    #define mp make_pair
    #define ps push_back
    #define fi first
    #define se second
    #define rei(x) scanf("%d",&x)
    #define rel(x) scanf("%lld",&x)
    #define ref(x) scanf("%lf",&x)
    
    typedef pair<int, int> pii;
    typedef pair<LL, LL> pll;
    
    const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
    const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
    const double pi = acos(-1.0);
    const int N = 2e3+100;
    
    int pre[N],n;
    map <int, int> dic;
    
    class Solution {
    public:
        bool splitArray(vector<int>& nums) {
            n = nums.size();
            pre[0] = nums[0];
            rep1(i, 1, n - 1)
                pre[i] = pre[i - 1] + nums[i];
            rep1(j, 1, n - 2)
            {
                dic.clear();
                int l = 0, r = j - 1;
                rep1(i, l + 1, r - 1)
                {
                    if (pre[i] - nums[i] == pre[r] - pre[i])
                    {
                        dic[pre[r] - pre[i]] = 1;
                    }
                }
    
                l = j + 1, r = n - 1;
                rep1(i, l + 1, r - 1)
                {
                    if (dic[pre[r] - pre[i]] && (pre[i] - nums[i] - pre[j]) == (pre[r] - pre[i]))
                        return true;
                }
            }
            return false;
        }
    };
  • 相关阅读:
    请求报文的方法及get与post的区别
    fiddler响应报文的headers属性详解
    fiddler请求报文的headers属性详解
    Session与Cookie的区别
    python学习之函数(四)--递归
    python学习之函数(四)--lambda表达式
    python学习之函数(三)--函数与过程
    python学习之函数(二)——参数
    python学习之序列
    python学习之函数(一)
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7626496.html
Copyright © 2011-2022 走看看