Day8力扣打卡

打卡记录

查找和替换模式(哈希表 / find函数查询重复程度)

链接

1.hash表双映射检测是否存在相同映射。

2.利用string的find函数返回下标来检测对应字符串的重复程度(妙)。

cpp 复制代码
class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        auto match = [&](string& s, string& p) -> bool
        {
            unordered_map<char, char> hash;
            for (int i = 0; i < s.size(); ++i)
            {
                char x = s[i], y = p[i];
                if (!hash.count(x)) hash[x] = y;
                else if (hash[x] != y) return false;
            }
            return  true;
        };
        vector<string> ans;
        for (auto& word : words)
            if (match(word, pattern) && match(pattern, word)) ans.push_back(word);
        return ans;
    }
};
cpp 复制代码
class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> ans;
        auto match = [&](string& s, string& p) -> bool
        {
            for (int i = 0; i < s.size(); ++i)
                if (s.find(s[i]) != p.find(p[i])) return false;
            return true;
        };
        for (auto& word : words)
            if (match(word, pattern)) ans.push_back(word);
        return ans;
    }
};

划分数组使最大差为 K(排序 + 贪心 + 移动窗口)

链接

由于求子序列的最大值与最小值,因此其顺序可以打乱,可以直接使用sort快排,然后贪心采用移动窗口来求最小分组数。

cpp 复制代码
class Solution 
{
public:
    int partitionArray(vector<int>& nums, int k) 
    {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        int res = 0, l = 0, r = 0;
        while (r < n)
        {
            if (nums[l] + k >= nums[r]) r++;
            else 
            {
                res++;
                l = r++;
            }
        }
        if (l < r) res ++;
        return res;
    }
};
相关推荐
历程里程碑17 小时前
普通数组---合并区间
java·大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎
Felven17 小时前
B. 250 Thousand Tons of TNT
算法
小老鼠不吃猫17 小时前
深入浅出(十三)QWT库——高稳定二维绘图
c++·qt·二维图
无忧.芙桃17 小时前
AVL树的实现
数据结构·c++
victory043118 小时前
PPO GAE优势函数演化和推导
算法
遥望九龙湖18 小时前
打包动态库
开发语言·c++·visualstudio
Jasmine_llq18 小时前
《P3572 [POI 2014] PTA-Little Bird》
算法·滑动窗口·单调队列·动态规划(dp)·多组查询处理·循环优化(宏定义 rep)
tankeven18 小时前
HJ101 排序
c++·算法
流云鹤18 小时前
动态规划02
算法·动态规划
小白菜又菜18 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode