力扣打卡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;
    }
    }

相关推荐
兰令水2 小时前
hot100【acm版】【2026.7.13打卡-java版本】
java·开发语言·数据结构·算法·leetcode·面试
Tisfy2 小时前
LeetCode 1291.顺次数:打表/枚举
算法·leetcode·题解·枚举·遍历
罗超驿3 小时前
双指针算法详解:从入门到精通(Java版)
算法·leetcode·职场和发展
tkevinjd3 小时前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
tkevinjd7 小时前
416分割等和子集
java·python·算法·leetcode·职场和发展
什巳18 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
鱼儿也有烦恼21 小时前
快速学完 LeetCode top 1~50
leetcode·algorithm
退休倒计时1 天前
【每日一题】LeetCode 17. 电话号码的字母组合 TypeScript
算法·leetcode·typescript
临沂堇1 天前
刷题日志 | LeetCode Hot 100 双指针
算法·leetcode·职场和发展
XWalnut1 天前
LeetCode刷题 day29
java·算法·leetcode