力扣 第 383 场周赛 解题报告 | KMP

力扣 第 383 场周赛 解题报告 | KMP

链接

前言


一个人能走的多远不在于他在顺境时能走的多快,而在于他在逆境时多久能找到曾经的自己。

T1 修改矩阵

思路:模拟
时间复杂度: O ( m n ) O(mn) O(mn)

class Solution:
    def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
        n, m = len(matrix), len(matrix[0])
        for j in range(m):
            mx = -inf
            for i in range(n):
                mx = max(mx, matrix[i][j])
            for i in range(n):
                if matrix[i][j] == -1:
                    matrix[i][j] = mx
        ans = matrix
        return ans

T2 T4 匹配模式数组的子数组数目

思路: KMP 匹配字符串

class Solution {
    int ne[1000010];
public:
    int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
        int n = nums.size(), m = pattern.size();
        
        ne[0] = -1;
        for (int i = 1, j = -1; i < m; i ++) {
            while (j != -1 and pattern[i] != pattern[j + 1])    j = ne[j];
            if (pattern[i] == pattern[j + 1])   j ++;
            ne[i] = j;
        }
        
        vector<int> v(n - 1);
        for (int i = 1; i < n; i ++) {
            if (nums[i] == nums[i-1])   v[i-1] = 0;
            else if (nums[i] > nums[i-1])   v[i-1] = 1;
            else    v[i-1] = -1;
        }
        
        int cnt = 0; 
        for (int i = 0, j = -1; i < n - 1; i ++) {
            while (j != -1 and pattern[j+1] != v[i])    j = ne[j];
            if (pattern[j+1] == v[i])   j ++;
            if (j == m - 1) {
                cnt ++;
                j = ne[j];
            }
        }
        return cnt;
    }
};

T3 回文字符串的最大数量
思路: 贪心

class Solution {
public:
    int maxPalindromesAfterOperations(vector<string>& words) {
        int odd = 0, even = 0, cnt = 0;
        unordered_map<char, int> mp;
        vector<int>  v;
        for (auto &s: words) {           
            int n = s.size();
            v.emplace_back(n);
            for (char &c: s)    mp[c] ++;
            
        }
        sort(v.begin(), v.end());
        for (auto it: mp) {
            int x = it.second;
            if (x % 2)  {
                odd ++;
                even += x - 1;
            }
            else {
                even += x;
            }
        }
        for (auto x: v) {
            if (x % 2) {
                if (odd) {
                    odd --;
                }
                else {
                    even -= 2;
                    odd ++;
                }
                x -= 1; 
            }
            if (even < x)   break;
            else {
                even -= x;
                cnt ++;
            }
        }
        return cnt;
    }
}  ;

你可能感兴趣的:(题解,leetcode,算法,职场和发展)