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;
    }
};
相关推荐
明月_清风3 分钟前
算法时间复杂度:给小白的一堂"算快慢"课
后端·算法
Zenova EdgeOS3 分钟前
等保 2.0 在工业网关的落地:测评点、整改、长期维护
c++·边缘计算·工业网关
vivo互联网技术7 分钟前
TinySR:面向真实世界图像超分辨率的轻量级扩散模型
人工智能·算法
铅笔小新z13 分钟前
【数据结构】顺序表和链表
数据结构·链表
不会就选b39 分钟前
数据结构之栈的算法题(OJ)
linux·数据结构·算法
牛油果子哥q1 小时前
C++大型项目工程精讲:CMake完整实战、静态库&动态库、模块化拆分、单元测试、gdb调试、性能工具、工程踩坑全解
开发语言·c++·单元测试
Dream Cosmos1 小时前
C++ 多态上篇:从 virtual 到抽象类,彻底理解多态的使用
开发语言·c++
人工智能培训1 小时前
人工智能性别与地域偏见的成因及消解路径
大数据·人工智能·算法·生活
鹿角片ljp1 小时前
LeetCode 56:合并区间复盘|从排序思维到 List<int[]> 的简洁写法
算法·leetcode·list
M78佐菲1 小时前
Linux学习笔记:网络通信
linux·笔记·学习·算法