爱奇艺2018年9月15日笔试编程题目AC代码

这几天一直在关注着工作的事情,师兄们做笔试题,我也跟着在刷,包括华为,百度,腾讯,阿里等公司的笔试题都做了,基本上都帮助师兄拿到了面试的资格,但是因为密度太大,而自己还要整理leetcode的学习笔记,所以,很多题目没有来得及整理,今天正好提前AC完成,就简单分享一下爱奇艺的两个题目。

第一个题目是,一个字符串,有六个符号,符号是从字符0到字符9的任意一个数,给定一个字符串后,你可以改变任意任何位置上的字符,目的是想让前三个字符的和与后三个字符的和相等,要求改变的字符位置尽可能少。刚开始只能通过82%,主要是只考虑一边改变的情况,而两边是可以同时改变的。下面是我AC的代码,写的超级简陋,刚刚笔试完就发的博客,有点仓促,其实可以做很多优化:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int res;
    string str = "";
    cin >> str;

    int left = str[0]+str[1]+str[2];
    int right = str[3]+str[4]+str[5];
    int dist = abs(left- right);

    if (!dist) {
        cout << dist << endl;
        return 0;
    }

    if (str[0] > str[1]) {
        swap (str[0], str[1]);
    }
    if (str[0] > str[2]) {
        swap (str[0], str[2]);
    }
    if (str[1] > str[2]) {
        swap (str[1], str[2]);
    }

    if (str[3] > str[4]) {
        swap (str[3], str[4]);
    }
    if (str[3] > str[5]) {
        swap (str[3], str[5]);
    }
    if (str[4] > str[5]) {
        swap (str[4], str[5]);
    }

    int minnums = 3;
    int nums = 0;

    int tmp = dist;
    while (tmp>0 && nums<3) {
        tmp -= ('9'-str[nums]);
        ++nums;
    }
    minnums = min(nums, minnums);

    tmp = dist;
    nums = 0;
    while (tmp>0 && nums<3) {
        tmp -= (str[2-nums]-'0');
        ++nums;
    }
    minnums = min(nums, minnums);

    tmp = dist;
    nums = 0;
    while (tmp>0 && nums<3) {
        tmp -= ('9'-str[nums+3]);
        ++nums;
    }
    minnums = min(nums, minnums);

    tmp = dist;
    nums = 0;
    while (tmp>0 && nums<3) {
        tmp -= (str[5-nums]-'0');
        ++nums;
    }
    minnums = min(nums, minnums);

    if (minnums == 3) {
        if (('9'-str[0]+str[5]-'0')>tmp || (str[3]-'0'+'9'-str[3])>tmp) {
            minnums = 2;
        }
    }

    cout << minnums << endl;
    return 0;
}

 第二个题目很简单,就是说,给定一组食物,每种食物的份数告诉,一个人每天要么吃一份食物,要么添一份食物,最后,经过M天,给出特定的某个食物份数的排名是多少?

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<int> A;
    int N = 0, M = 0, P = 0;
    cin >> N >> M >> P;

    for (int i=0; i<N; ++i) {
        int ai = 0;
        cin >> ai;
        A.push_back(ai);
    }

    for (int i=0; i<M; ++i) {
        char ab = 0;
        int num = 0;
        cin >> ab >> num;

        if (num <= N && num >= 0) {
            if (ab == 'A') {
                ++A[num-1];
            } else if (A[num-1] > 0) {
                --A[num-1];
            }
        }
    }

    int res = 1;
    for (int i=0; i<N; ++i) {
        if (i != (P-1) && A[i]>A[P-1]) {
            ++res;
        }
    }

    cout << res << endl;

    for (int i=0; i<A.size(); ++i) {
        cout << A[i] << " ";
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_29592167/article/details/82712570