网易——疯狂队列

int main(){
    int n;
    cin>>n;
    vector<int> height;
    for (int i = 0; i<n; i++) {
        int a;
        cin>>a;
        height.push_back(a); 
    }
    sort(height.begin(),height.end()); //先对输入的数组排序
    int i = 0;
    int j = n - 1;    //每次取两个插入,一个从小到大取,一个从大到小取
    deque<int> re;
    re.push_back(height[n - 1]);
    j--;
    re.push_back(height[0]);
    i++;
    while (i < j) { 
        if (re.front() >= re.back()) {
            re.push_back(height[j]);      //判断大的数是从后面插入还是前面
        } else {
            re.push_front(height[j]);
        }
        if (re.front() >= re.back()) {
            re.push_front(height[i]);     //判断小的数是从后面插入还是前面
        } else {
            re.push_back(height[i]);
        }
        i++;
        j--;
    }
    if (i == j) {                        //如果数组是奇数,还有一个数没插入
        if (re.front() >= re.back()) {
            re.push_back(height[i]);
        } else {
            re.push_front(height[i]);
        }
    }
    vector<int> x;             //因为不知道怎么用deque直接求差,所以转换成了vector,有点搓,求大家指导
    while (!re.empty()) {
        x.push_back(re.front());
        re.pop_front();
    }
    int y = 0;
    for (int i = 1; i<n; i++) {
        y += abs(x[i] - x[i - 1]);
    }
    cout<<y;
    return 0;
}

全部评论
用队列会变得非常简单。。。
点赞 回复 分享
发布于 2017-08-13 01:03
你是面试什么的
点赞 回复 分享
发布于 2017-08-12 21:51
不需要队列的吧,用队列的思想,只保存最左边和最右边的就可以了,虽然我用了队列,后来不想改了=。=
点赞 回复 分享
发布于 2017-08-12 17:58
用迭代器求差
点赞 回复 分享
发布于 2017-08-12 17:57

相关推荐

11-17 11:15
门头沟学院 Java
金山办公终于发offer了,但薪资和平台都不如已有的offer打算拒了,A不了薪资,不满意直接拒了,留给需要的人嘿嘿嘿时间线:10.14线下一面&nbsp;,10.23线上二面,下午发测评,11月1日HR面,11月14日电话谈薪,11月17日直接发offer
star__plat...:好兄弟干的好啊,解气。金山第一次笔难度高的离谱,第二次简单的离谱全A了,用人部门筛选中估计最后还是要挂我,就这今早智联招聘还给我发信息让我投
offer帮选
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务