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;
    }
};
相关推荐
一条星星鱼14 分钟前
从0到1:如何用统计学“看透”不同睡眠PSG数据集的差异(域偏差分析实战)
人工智能·深度学习·算法·概率论·归一化·睡眠psg
浮灯Foden15 分钟前
算法-每日一题(DAY18)多数元素
开发语言·数据结构·c++·算法·leetcode·面试
小欣加油36 分钟前
leetcode 844 比较含退格的字符串
算法·leetcode·职场和发展
小龙报37 分钟前
《算法每日一题(1)--- 第31场蓝桥算法挑战赛》
c语言·开发语言·c++·git·算法·学习方法
llz_11239 分钟前
五子棋小游戏
开发语言·c++·算法
liulilittle40 分钟前
在 Android Shell 终端上直接运行 OPENPPP2 网关路由配置指南
android·linux·开发语言·网络·c++·编程语言·通信
violet-lz1 小时前
数据结构八大排序:归并排序-原理+C语言实现+优化+面试题
c语言·数据结构·排序算法
如竟没有火炬1 小时前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
嵌入式小李.man1 小时前
C++第十三篇:继承
开发语言·c++
寂静山林1 小时前
UVa 12526 Cellphone Typing
算法