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

相关推荐
Nil2081 小时前
leetcode 105从前序和中序遍历序列构造二叉树
算法·leetcode·职场和发展
Nil2082 小时前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
cz07102 小时前
hot100_搜索二维矩阵 II
算法·leetcode
圣保罗的大教堂4 小时前
leetcode 3718. 缺失的最小倍数 简单
leetcode
青 春 记 忆5 小时前
LeetCode 234. 回文链表|Python 解法详解
python·leetcode·链表
啊嘞嘞?7 小时前
力扣(LRU缓存)
算法·leetcode
啊嘞嘞?7 小时前
力扣(下一个排列)
算法·leetcode
Forever Nore8 小时前
LeetCode 16 最接近的三数之和 - 双指针逼近
算法·leetcode·职场和发展
smj2302_796826528 小时前
解决leetcode第4033题有效K个不同元素子数组I
数据结构·python·算法·leetcode
rannn_1118 小时前
【力扣hot100】回溯专题|全排列、子集、字母组合、组合总和、括号生成、单词搜索、分割回文串、N皇后
java·算法·leetcode·回溯