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;
    }
};
相关推荐
小O的算法实验室13 分钟前
2024年IEEE TITS SCI2区TOP,考虑无人机能耗与时间窗的卡车–无人机协同路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
派森先生14 分钟前
排序算法-选择排序
算法·排序算法
C雨后彩虹18 分钟前
书籍叠放问题
java·数据结构·算法·华为·面试
ghie909021 分钟前
GPS抗干扰算法MATLAB实现
开发语言·算法·matlab
格林威24 分钟前
基于轮廓特征的工件分类识别:实现无模板快速分拣的 8 个核心算法,附 OpenCV+Halcon 实战代码!
人工智能·数码相机·opencv·算法·目标跟踪·分类·数据挖掘
Jasmine_llq25 分钟前
《UVA11181 条件概率 Probability|Given》
数据结构·算法·深度优先搜索(dfs)·剪枝(可行性剪枝)·组合枚举(递归暴力枚举)·条件概率统计与归一化
老鼠只爱大米31 分钟前
LeetCode算法题详解 560:和为K的子数组
算法·leetcode·前缀和·哈希表·子数组求和·subarraysum
MM_MS33 分钟前
Halcon小案例--->路由器散热口个数(两种方法)
人工智能·算法·目标检测·计算机视觉·视觉检测·智能路由器·视觉
小杨同学4933 分钟前
C 语言实战:超市水果结算系统(深度解析与优化)
后端·算法·设计
编程之路,妙趣横生36 分钟前
C++ IO流
c++