力扣打卡day05——找到字符串中所有字母异位词、和为K的子数组

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

复制代码
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        int slen=s.length();
        int plen=p.length();
        if(slen<plen){
            return  new ArrayList<Integer>();
        }
        List<Integer>  list=new ArrayList<>();
        int [] scount=new int[26];
        int [] pcount=new  int[26];
        for(int i=0;i<plen;i++){
             pcount[p.charAt(i)-'a']++;  //p的窗口的值,不变
             scount[s.charAt(i)-'a']++;  //s窗口的值,可变
        }
//判断放置处是否有异位词。若相等,则表明s的前几位就是p的异位词。起始索引即为0.
        if(Arrays.equals(pcount,scount)){
            list.add(0);
        }
        //判断的就是索引为1及以后的啦
        for(int i=0;i<slen-plen;i++){
            // 减去滑动窗口的第0位
            scount[s.charAt(i)-'a']--;
            // 加上窗口的第plen位(第3位)
            scount[s.charAt(i+plen)-'a']++;
            if(Arrays.equals(pcount,scount)){
            list.add(i+1);
        }
        }
           return list;
    }
}

560. 和为 K 的子数组 - 力扣(LeetCode)

思路:

  1. 核心公式:pre[i] - pre[j] = k → 找 pre[j] = pre[i] - k 的次数;

  2. 哈希表作用:记录每个前缀和出现的次数,避免重复计算;

  3. 初始化 map.put(0,1):处理「从数组开头到当前元素」的子数组和 = k 的情况;

  4. 时间复杂度 O (n),空间复杂度 O (n)(最优解)。

    class Solution {
    public int subarraySum(int[] nums, int k) {
    //前缀和 +哈希表
    int count=0;
    int pre=0;
    // key:前缀和,value:该前缀和出现的次数
    Map<Integer,Integer> map=new HashMap<>();
    map.put(0, 1);// 初始化:前缀和0出现1次(处理从第0个元素开始的子数组
    for(int i=0;i<nums.length;i++){
    pre+=nums[i]; //统计每个前缀和
    if(map.containsKey(pre-k)){
    // 次数累加
    count+=map.get(pre-k);
    }
    // 把当前前缀和存入map,次数+1(如果已存在就取原有值+1,否则0+1)
    map.put(pre,map.getOrDefault(pre,0)+1);
    }
    return count;
    }
    }

相关推荐
穿条秋裤到处跑1 天前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
水蓝烟雨1 天前
1931. 用三种不同颜色为网格涂色
算法·leetcode
leoufung1 天前
LeetCode 76:Minimum Window Substring 题解与滑动窗口思维详解
算法·leetcode·职场和发展
风筝在晴天搁浅1 天前
LeetCode 92.反转链表Ⅱ
算法·leetcode·链表
普贤莲花2 天前
【2026年第18周---写于20260501】---舍得
程序人生·算法·leetcode
m0_629494732 天前
LeetCode 热题 100-----16.除了自身以外数组的乘积
数据结构·算法·leetcode
We་ct2 天前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划
无敌昊哥战神2 天前
【LeetCode 37】解数独 (Sudoku Solver) —— 回溯法详解 (Python/C/C++)
c语言·c++·python·算法·leetcode
风筝在晴天搁浅2 天前
LeetCode 162.寻找峰值
算法·leetcode
罗超驿2 天前
双指针算法经典案例:LeetCode 283. 移动零(Java详解)
java·算法·leetcode