欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 41双周赛

程序员文章站 2022-03-05 18:29:01
...

完成了三题,至于hard题,我曾试图翻译成人类语言,对此我表示很抱歉~。

题1解题代码:

class Solution {
public:
    int countConsistentStrings(string allowed, vector<string>& words) {
            unordered_set<char> e;
            for(auto &n:allowed)
            {
                e.emplace(n);
            }
            int i=0;
            int sum=0;
            while(i<words.size())
            {
                int j=0;
                while(j<words[i].size())
                {
                    if(e.find(words[i][j])==e.end())
                        break;
                    j++;
                }
                if(j==words[i].size())sum++;
                i++;
            }
        return sum;
    }
};

题2解题代码:

class Solution {
public:
    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
        int i=1;
        vector<int> res(nums.size());
        int t=0;
        while(i<nums.size())
        {
            t+=abs(nums[i]-nums[0]);
            i++;
        }
        res[0]=t;
        i=1;
        while(i<nums.size())
        {
            res[i]=res[i-1]+(nums[i]-nums[i-1])*(i-1)-(nums[i]-nums[i-1])*(nums.size()-1-i);
            i++;
        }
        return res;
    }
};

题3解题代码:

class Solution {
public:
    int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) {
        vector<int> q(aliceValues.size());
        int i = 0;
        while (i < aliceValues.size())
        {
            q[i] = aliceValues[i] + bobValues[i];
            i++;
        }
        sor(q, aliceValues, bobValues, 0, bobValues.size() - 1);
        int n1 = 0;
        int n2 = 0;
        i = aliceValues.size() - 1;
        int j = 0;
        while (i > -1)
        {
            if (!j) { n1 += aliceValues[i]; j = 1; }
            else { n2 += bobValues[i]; j = 0; }
            i--;
        }
        if (n1 > n2)return 1;
        else if (n1 == n2)return 0;
        else
            return -1;
    };
    void sor(vector<int>& a, vector<int>& b, vector<int>& c, int left, int right)
    {
        if (left >= right)
            return;
        int i = left;
        int j = right;
        int k1 = a[left];
        int k2 = b[left];
        int k3 = c[left];
        while (i < j)
        {
            while (i < j && k1 <= a[j])
                j--;
            a[i] = a[j];
            b[i] = b[j];
            c[i] = c[j];
            while (i < j && k1 >= a[i])
                i++;
            a[j] = a[i];
            b[j] = b[i];
            c[j] = c[i];
        }
        a[i] = k1;
        b[i] = k2;
        c[i] = k3;
        sor(a, b, c, left, i - 1);
        sor(a, b, c, i + 1, right);
    }
};