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;
    }
};
相关推荐
Gyoku Mint37 分钟前
机器学习×第五卷:线性回归入门——她不再模仿,而开始试着理解你
人工智能·python·算法·机器学习·pycharm·回归·线性回归
weixin_457665391 小时前
C++11新标准
开发语言·c++
蒙奇D索大1 小时前
【数据结构】图论最短路径算法深度解析:从BFS基础到全算法综述
数据结构·算法·图论·广度优先·图搜索算法
trouvaille1 小时前
哈希数据结构的增强
算法·go
我不是小upper1 小时前
L1和L2核心区别 !!--part 2
人工智能·深度学习·算法·机器学习
奔跑吧邓邓子2 小时前
解锁Vscode:C/C++环境配置超详细指南
c语言·c++·vscode·配置指南
虾球xz2 小时前
CppCon 2015 学习:Reactive Stream Processing in Industrial IoT using DDS and Rx
开发语言·c++·物联网·学习
liujing102329293 小时前
Day09_刷题niuke20250609
java·c++·算法
不7夜宵3 小时前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表
Bardb3 小时前
02__C++的基本语法
c++·qt