LeetCode 2799、2840题解

使用hashmap加滑动窗口解决问题

例如List[1,3,1,2,2]

我们通过hashmap.put(nums[i],hashmap.getOrDefault(nums[i],0)+1)后再通过hashmap.size()获取键值对的数量,即不同值的数量。

滑动窗口思想如上所示:

复制代码
class Solution {

    public int countCompleteSubarrays(int[] nums) {

        int n = 0;

        HashMap<Integer,Integer> map = new HashMap<>();

        for(int i=0;i<nums.length;i++){

            map.put(nums[i],map.getOrDefault(nums[i],0)+1);

        }

        n = map.size();

        System.out.println("n:"+n);

  

        int left = 0;

        int right = n;

        int total = 0;

        while(right<=nums.length){

            HashMap<Integer,Integer> hashmap = new HashMap<>();

            for(int i=left;i<nums.length;i++){

                hashmap.put(nums[i],hashmap.getOrDefault(nums[i],0)+1);

                if(hashmap.size()==n) total++;

            }

            left++;

            right = n+left;

        }

        return total;

    }

}

如图所示为一种解决方法,也可以使用二维数组解决

复制代码
class Solution {

    public boolean checkStrings(String s1, String s2) {

        int[][] cnt1 = new int[2][26];

        int[][] cnt2 = new int[2][26];

        for (int i = 0; i < s1.length(); i++) {

            cnt1[i % 2][s1.charAt(i) - 'a']++;

            cnt2[i % 2][s2.charAt(i) - 'a']++;

        }

        return Arrays.deepEquals(cnt1, cnt2);

    }

}
相关推荐
旖-旎22 分钟前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC1 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn2 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹2 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术2 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber5 小时前
检索技术的实际应用
人工智能·算法
hhzz6 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_6 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI7 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅