代码随想录3哈希表

2 有效的字母异位词

Leetcode242 用int[26]当map

Leetcode49

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for(String str:strs){
            int[] counts = new int[26];
            int length = str.length();
            for(int i=0;i<length;i++){
                counts[str.charAt(i)-'a']++;
            }
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<26;i++){
                if(counts[i]!=0){
                    sb.append((char)('a'+i));
                    sb.append(counts[i]);
                }
            }
            String key = sb.toString();
            List<String> list = map.getOrDefault(key,new ArrayList<String>());
            list.add(str);
            map.put(key,list);
        }
        return new ArrayList<List<String>>(map.values());
    }
}

Leetcode438

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> ans = new ArrayList<>();
        int[] sCount = new int[26];
        int[] pCount = new int[26];
        for(int i=0;i<pLen;i++){
            sCount[s.charAt(i)-'a']++;
            pCount[p.charAt(i)-'a']++;
        }
        if(Arrays.equals(sCount,pCount)){
            ans.add(0);
        }
        for(int i=0;i<sLen-pLen;i++){
            sCount[s.charAt(i)-'a']--;
            sCount[s.charAt(i+pLen)-'a']++;
            if(Arrays.equals(sCount,pCount)){
                ans.add(i+1);
            }
        }
        return ans;
    }
}

3 两个数组的交集

Leetcode349 用set

Leetcode350

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer,Integer> map = new HashMap<>();
        // Map<Integer,Integer> res = new HashMap<>();
        int m = nums1.length;
        int n = nums2.length;
        int[] res = new int[m];

        for(int i=0;i<m;i++){
            map.put(nums1[i],map.getOrDefault(nums1[i],0)+1);
        }
        int idx = 0;
        for(int i=0;i<n;i++){
            if(map.containsKey(nums2[i])){
                map.put(nums2[i],map.get(nums2[i])-1);
                res[idx++]=nums2[i];
                if(map.get(nums2[i])==0){
                    map.remove(nums2[i]);
                }
            }
        }

        return Arrays.copyOfRange(res,0,idx);
    }
}

4 快乐数

Leetcode202 用set存每个n

5 两数之和

Leetcode1 map存nums[i]和i

6 四数相加

Leetcode454 两两组合->类似两数之和

7 赎金信

Leetcode383 用int[26]当map

8 三数之和

Leetcode15 遍历一个i,剩下两个用双指针

9 四数之和

Leetcode18 比三数之和多一层for

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值