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;
    }
};
相关推荐
xiaoye-duck4 分钟前
《算法题讲解指南:优选算法-链表》--51.两数相加,52.两两交换链表中的节点
数据结构·算法·链表
Cosolar8 分钟前
阿里CoPaw进阶使用手册:从新手到高手的完整指南
人工智能·后端·算法
代码改善世界15 分钟前
【数据结构】八大排序算法详解(C语言实现)|插入排序、希尔排序、选择排序、堆排序、冒泡排序、快速排序、归并排序、计数排序
c语言·数据结构·排序算法
松小白song22 分钟前
机器人路径规划算法之Dijkstra算法详解+MATLAB代码实现
前端·javascript·算法
qq_263_tohua28 分钟前
第107期 刷算法题
算法
2501_9403152629 分钟前
98验证二叉搜索树
java·数据结构·算法
luckycoding35 分钟前
3005. 最大频率元素计数
算法·leetcode·职场和发展
像污秽一样35 分钟前
算法设计与分析-算法效率分析基础-分治法
算法·排序算法
我能坚持多久36 分钟前
栈与队列OJ问题详解
算法
ouliten37 分钟前
C++笔记:std::numeric_limits
c++·笔记