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

相关推荐
YLCHUP7 小时前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法
(●—●)橘子……7 小时前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
wenyq78 小时前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
文丑颜不良啊8 小时前
LeetCode1181~1200题目解析
java·leetcode
海绵宝宝转agent9 小时前
Leetcode100+面经
java·笔记·学习·算法·leetcode·深度优先
Shaoshing9 小时前
LeetCode100 283.移动零
java·数据结构·算法·leetcode
文丑颜不良啊9 小时前
LeetCode1201~1220题目解析
java·leetcode
文丑颜不良啊9 小时前
LeetCode1161~1180题目解析
java·leetcode
一去不复返的通信er19 小时前
贪心算法-合并区间(LeetCode 56)
算法·leetcode·贪心算法
INGNIGHT1 天前
91 · 最小调整代价(序列dp)
数据结构·算法·leetcode