每日两题 / 438. 找到字符串中所有字母异位词 && 238. 除自身以外数组的乘积(LeetCode热题100)

438. 找到字符串中所有字母异位词 - 力扣(LeetCode)

记录p串每个字符出现次数

维护与p串等长的滑动窗口,记录其中每个字符的出现次数

每次滑动后将当前次数与p串的次数比较即可

cpp 复制代码
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        unordered_map<char, int> mp, cnt;
        for (auto t : p)
            cnt[t] ++ ;
        for (int i = 0; i < p.size() - 1 && i < s.size(); ++ i)
            mp[s[i]] ++ ;
        vector<int> ans;
        for (int r = p.size() - 1, l = 0; r < s.size(); ++ r, ++ l)
        {
            mp[s[r]] ++ ;
            bool flag = true;
            for (auto t : mp)
            {
                if (t.second != cnt[t.first])
                {
                    flag = false;
                    break;
                }
            }
            mp[s[l]] -- ;
            if (flag) ans.push_back(l);
        }
        return ans;
    }
};

238. 除自身以外数组的乘积 - 力扣(LeetCode)

维护"前缀和"与"后缀和"数组即可

由于用nums作为前缀和数组,ans作为后缀和数组,即可达到空间复杂度为 O ( 1 ) O(1) O(1) 的要求

cpp 复制代码
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> ans = nums;
        for (int i = 1; i < nums.size(); ++ i)
            nums[i] *= nums[i - 1];
        for (int i = ans.size() - 2; i >= 0; -- i)
            ans[i] *= ans[i + 1];
        for (int i = 0; i < ans.size(); ++ i)
        {
            if (i == 0) ans[i] = ans[i + 1];
            else if (i == ans.size() - 1) ans[i] = nums[i - 1];
            else ans[i] = nums[i - 1] * ans[i + 1];
        }
        return ans;
    }
};
相关推荐
weixin_4461224611 分钟前
LinkedList剖析
算法
百年孤独_1 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程2 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生2 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生2 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧2 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao2 小时前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展
ゞ 正在缓冲99%…2 小时前
leetcode67.二进制求和
算法·leetcode·位运算
YuTaoShao2 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II——排除法
java·算法·leetcode