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);

    }

}
相关推荐
程序员-King.5 分钟前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
转基因37 分钟前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
我想进大厂2 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论
@Aurora.2 小时前
数据结构手撕--【二叉树】
数据结构·算法
victd2 小时前
什么是AutoRec?
算法
陈壮实的搬砖日记2 小时前
抛硬币背后的秘密-通俗玩转二项分布
算法
前端 贾公子2 小时前
力扣 83 . 删除排序链表中的重复元素:深入解析与实现
数据结构·算法
Y1nhl2 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
oioihoii2 小时前
C++23 中 constexpr 的重要改动
c++·算法·c++23
前端 贾公子2 小时前
详解 LeetCode 第 242 题 - 有效的字母组
算法·leetcode·职场和发展