力扣打卡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 热题 100——day2 字母异位词分组
c++·算法·leetcode
雪碧聊技术5 小时前
力扣 72. 编辑距离——动态规划经典例题
算法·leetcode·动态规划
木井巳5 小时前
【DFS解决floodfill算法】岛屿的最大面积
java·算法·leetcode·深度优先
yyds_yyd_100865 小时前
877. 石子游戏(2026.08.02)& 486. 预测赢家(2026.08.01)
c++·leetcode
普通攻击往后拉17 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
橘子汽水1681 天前
Leetcode 230,98:二叉搜索树中第K小的元素,验证二叉搜索树
算法·leetcode·职场和发展
普通攻击往后拉1 天前
Leetcode 448. 找到所有数组中消失的数字
算法·leetcode·职场和发展
mifengxing1 天前
LeetCode 189 轮转数组|3种解法拆解,从暴力到O(1)原地最优解
数据结构·算法·leetcode
程序员-珍1 天前
力扣 877. 石子游戏
算法·leetcode·游戏
wabs6661 天前
关于链表【力扣19.删除链表的倒数第N个节点的思考】
数据结构·leetcode·链表