LeetCode每日一题:2月19日~2月23日

煎饼排序

每一次翻转将前n个数最大值放到序列最后,保证可以在2*n次数下翻转完成

class Solution {
public:
    vector<int> pancakeSort(vector<int>& a) {
        vector<int> res;
        for (int n = a.size(); n >= 2; n -- ) {
            int k = max_element(a.begin(), a.begin() + n) - a.begin();
            if (k == n - 1) continue;

            reverse(a.begin(), a.begin() + k + 1);
            reverse(a.begin(), a.begin() + n);
            res.push_back(k + 1);
            res.push_back(n);
        }
        return res;
    }
};

717. 1 比特与 2 比特字符

class Solution {
public:
    bool isOneBitCharacter(vector<int>& bits) {
        int idx = 0, n = bits.size();
        while (idx < n - 1) {
            idx += bits[idx] + 1;
        }
        return idx == n - 1;
    }
};

838. 推多米诺

用两个数组分别存每一个倒下的多米诺骨牌影响范围,比较该骨牌收到哪边的影响大,收到力大的反方向倒

class Solution {
public:
    string pushDominoes(string d) {
        string res;
        int n = d.size();
        vector<int> l(n, 100000), r(n, 100000);
        for (int i = 0; i < n; i ++ ) {
            if (d[i] != 'R') continue;
            int j = i + 1;
            r[i] = 1;
            while (j < n && d[j] == '.')
                r[j ++ ] = j - i + 1;
            i = j - 1;
        }

        for (int i = n - 1; i >= 0; i -- ) {
            if (d[i] != 'L') continue;
            int j = i - 1;
            l[i] = 1;
            while (j >= 0 && d[j] == '.')
                l[j -- ] = i - j + 1;
            i = j + 1;
        }
        
        for (int i = 0; i < n; i ++ ) {
            if (l[i] > r[i]) res.push_back('R');
            else if (l[i] < r[i]) res.push_back('L');
            else res.push_back('.');
        }
        return res;
    }
};

好子集的数目

还没学

仅仅翻转字母

双指针模板题

class Solution {
public:
    bool is_al(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }
    string reverseOnlyLetters(string s) {
        int n = s.size();
        string a = s;
        for (int i = 0, j = n - 1; i < j; i ++ ) {
            if (!is_al(s[i])) continue;
            while (j > i && !is_al(s[j])) j -- ;
            swap(s[i], s[j]);
            j -- ;
        }
        return s;
    }
};

你可能感兴趣的:(每日一题,Leetcode刷题,leetcode,算法,职场和发展,动态规划)