美团2021校招真题002-小美的仓库整理

先附上自己最开始写的版本,思路就是暴力遍历
时间复杂度O(n^2)理所当然的超时了QWQ

#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <time.h>
#include <queue>
#include <cstring>
#include <set>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
int Weightest(vector<int>& weight,int n)
//取走货物的分割点设为0,遍历所有货物,计算最大区间和
{
    weight[n-1]=0;
    int temp=0,res=0;
    for(int i=0;i<weight.size();i++)
    {
        if(weight[i]==0)
        {
            res=res>temp?res:temp;
            temp=0;
        }
        else
        {
            temp+=weight[i];
        }
        if(i==weight.size()-1)
        //遍历到最后一件货物比较当前区间和与当前最大区间和
        {
            res=res>temp?res:temp;
        }
    }
    return res;
}
int main()
{
    int i, n,temp;
    cin >> n;
    if(n==0) return 0;
    vector<int> wei(n);
    for (i = 0; i < n; i++)
    {
        cin>>temp;
        wei[i]=temp;
    }
    for (i = 0; i < n; i++)
    {
        cin>>temp;
        cout<<Weightest(wei,temp)<<endl;
    }
    system("pause");
    return 0;
}

再来看参考自高赞第一篇题解的解法,成功AC。感谢大佬
主要难点在于怎样降低每次分割后搜寻最大区间和的时间复杂度,以下代码通过使用前缀和数组以及两种有序容器即setmap分别保存分割点和区间和使得时间复杂度由常规顺序遍历的n降低为logN(有序容器的查找、插入和删除操作均摊为 logN)
LeetCode参考题解

#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <time.h>
#include <queue>
#include <cstring>
#include <set>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;

int prefix[50050];
std::map<int, int> mmap;//map用于保存区间和的值,默认升序
std::set<int> bound;//set用于存储分割点,默认升序
int main() {
    int n;
    scanf("%d", &n);
    int w;
    memset(prefix, 0, sizeof(prefix));//初始化函数
    for (int i = 0; i < n; i++) {
        scanf("%d", &w);
        prefix[i + 1] = prefix[i] + w;
    }
    int pos;
    //初始化左右边界为数组边界
    bound.insert(0);
    bound.insert(n + 1);
    for (int i = 0; i < n; i++) {
        scanf("%d", &pos);
        auto idx = bound.lower_bound(pos);
        // 由于 set 的迭代器只能自减,所以先给 right 赋值
        int right = *idx, left = *(--idx);//找到分割点的左右边界
        int seg = prefix[right - 1] - prefix[left];
        //分割之前先把map里面保存的分割前的区间和清除或减一(存在多个相等和的区间时)
        if (mmap.find(seg) != mmap.end()) {
            if (mmap[seg] == 1) {
                mmap.erase(seg);
            } else {
                mmap[seg]--;
            }
        }
        //分割后保存新增的两个区间和
        int left_sum = prefix[pos - 1] - prefix[left];
        int right_sum = prefix[right - 1] - prefix[pos];
        //保存分割点
        bound.insert(pos);
        mmap[left_sum]++;
        mmap[right_sum]++;
        printf("%d\n", mmap.rbegin()->first);
        //map默认升序,返回尾端值
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值