首页 > 其他分享 >哈希表

哈希表

时间:2024-01-21 20:55:07浏览次数:20  
标签:right nums int ++ 哈希 new left

当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法

1.Java HashMap getOrDefault() 方法

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // 创建一个 HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // 往 HashMap 添加一些元素
        sites.put(1, "Google");
        sites.put(2, "Runoob");

        // key 的映射存在于 HashMap 中
        // Not Found - 如果 HashMap 中没有该 key,则返回默认值
        String value1 = sites.getOrDefault(1, "Not Found");
        System.out.println("Value for key 1:  " + value1);

        // key 的映射不存在于 HashMap 中
        // Not Found - 如果 HashMap 中没有该 key,则返回默认值
        String value2 = sites.getOrDefault(4, "Not Found");
        System.out.println("Value for key 4: " + value2);
    }
}
Value for key 1:  Google
Value for key 4: Not Found

2.力扣49-字母异位词分组-哈希表

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if(strs == null || strs.length == 0){
            return new ArrayList();
        }

        //创建一个哈希表
        Map<String, List> map = new HashMap<String,List>();
        for(String s: strs){
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String key = String.valueOf(chars);
            //判断哈希表中是否已有该key值
            if(!map.containsKey(key)){
                map.put(key,new ArrayList());
            }
            //将该字符串放在对应的key的list中
            map.get(key).add(s);
        }
        //返回map中所有键值对象构成的list
        return new ArrayList(map.values());
    }
}

3.力扣438-找到字符串中所有的字符异位词-滑动窗口

class Solution {
    public static boolean check(int[] a, int[] b){
        for(int i = 0; i < 26; i ++){
            if(a[i] != b[i]) return false;
        }
        return true;
    }
    
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> ans = new ArrayList<>();
        int n = s.length(), m = p.length();
        int[] c1 = new int[26], c2 = new int[26];
        for(int i = 0; i < m; i ++){
            c2[p.charAt(i) - 'a'] ++;
        }
        for(int l = 0, r = 0; r < n; r ++){
            c1[s.charAt(r) - 'a'] ++;
            if(r - l + 1 > m) c1[s.charAt(l ++) - 'a'] --;
            if(check(c1, c2)) ans.add(l);
        }
        return ans;
    }
}

4.将结果集合转为数组
Set resSet = new HashSet<>();
int[]
return resSet.stream().mapToInt(x -> x).toArray();
5.一些规范




6.力扣349、350-两个数组的交集

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1.length == 0 || nums1 == null || nums2 == null || nums2.length == 0)
            return new int[0];
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for(int i :nums1){
            set1.add(i);
        }
        for(int j :nums2){
            if(set1.contains(j)){
                set2.add(j);
            }
        }
        return set2.stream().mapToInt(x -> x).toArray();
    }
}

5.关于Arrays.copyOfRange()方法的使用
用于对一个已有的数组进行截取复制,复制出一个左闭右开区间的数组。
6.该方法是将数组转化成List集合的方法。
List list = Arrays.asList("a","b","c");
7.力扣15-三数之和-双指针、一层循环

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i ++){
            if(nums[i] > 0) return result;//每次循环,如果第一个数就大于0,那么就可以结束循环了
            if(i > 0 && nums[i] == nums[i - 1]) continue;//第一个数去重(从第二个数开始,如果和前面一  样,就可以结束这一次循环了
            int left = i + 1;
            int right = nums.length - 1;
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if(sum > 0) right --;
                else if (sum < 0) left ++;
                else{
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left ++;
                    right --;
                    while(right > left && nums[right] == nums[right + 1]) right --;
                    while(left < right && nums[left] == nums[left - 1]) left ++;
                }
            }
        }
        return result;
    }
}

8.力扣18-四数之和-双指针、两层循环嵌套

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);

        for(int i = 0; i < nums.length; i ++){
            if(nums[i] > 0 && nums[i] > target) return result;
            if(i > 0 && nums[i - 1] == nums[i]) continue;
            for(int j = i + 1; j < nums.length; j ++){
                if(j > i + 1 && nums[j - 1] == nums[j]) continue;
                int left = j + 1;
                int right = nums.length - 1;
                while(left < right){
                    long sum = (long)(nums[i] + nums[j] + nums[left] + nums[right]);
                    if(sum > target) right --;
                    else if(sum < target) left ++;
                    else{
                        result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        left ++;
                        right --;
                        while(left < right && nums[left - 1] == nums[left]) left ++;
                        while(right > left && nums[right + 1] == nums[right]) right --;
                    }
                }
            } 
        }
        return result;
    }
}

标签:right,nums,int,++,哈希,new,left
From: https://www.cnblogs.com/wusuoweiju/p/17978353

相关文章

  • 「笔记」哈希
    目录写在前面哈希是什么?写在最后写在前面大部分内容来自高中时期讲课PPT,在这里整理成了适合自学的形式。哈希是什么?一种用于统计复杂信息的的不完美算法。构造一个满射[1]的哈希函数,将复杂信息映射到便于统计的信息上。丢失了部分信息。写在最后进度有点太赶了!题单太难......
  • 哈希表的应用
    也是滑动窗口的应用,但用到了哈希表。哈希表一个索引,一个真值。索引可以是任何符号,因此可以表示一个事物的数量关系和对应关系.删除某个索引及真值时,要用迭代器,erase(it)。find是查找索引返回迭代器。点击查看代码classSolution{public:inttotalFruit(vector<int>&fr......
  • php rsa加密(非对称)实例 以及使用哈希256进行加密
    functiongetEncryptionUserID($client_secret):string{$str="-----BEGINPUBLICKEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpw/k/rPHx4c1nEO8lQr8Fkz2MMTnqNbspRox1f2snoDNcssTQxg9TyBOMujQy14eRibKE+X+qPVeZJyyfruTrtvB4EomJL7v4URcacg7H00A2HL1nf7......
  • 字母异位词分组【哈希】
    Problem:49.字母异位词分组文章目录思路解题方法复杂度Code思路hash解题方法对于每一个字符串,都按字符从小打到进行排序,然后用hash去存,如果排序后的结果在hash表里面存在的话,那么就只需要把这个字符串加入进行;如果不存在,就新建一个键值对就可以了。关键就是字符串没有排序,所以......
  • 两数之和【哈希】
    Problem:1.两数之和文章目录思路解题方法复杂度Code思路n方可以暴力,也可以用hash去降低时间复杂度。解题方法遍历列表,每个数都看一下是否它的补是否再hash表里面,在就说明找到了,不在就把它放进去,然后继续遍历。复杂度时间复杂度:添加时间复杂度,示例:空间复杂度:添加空间复杂度......
  • 字符串和哈希表的基本用法总结
    2287.重排字符形成目标字符串解决代码classSolution{publicintrearrangeCharacters(Strings,Stringtarget){Map<Character,Integer>sCounts=newHashMap<Character,Integer>();Map<Character,Integer>targetCounts=newHashMap&......
  • 网络攻防技术——哈希碰撞
    实验3:MD5碰撞试验实验内容:本次实验主要是加深大家对MD5碰撞及其原理的理解,使用SEED实验环境中的工具及编程语言,完成以下任务:使用md5collgen生成两个MD5值相同的文件,并利用bless十六进制编辑器查看输出的两个文件,描述你观察到的情况;参考Lab3_task2.c的代码,生成两个MD5值相同但......
  • 哈希冲突
    我们先模拟一下,其实题目就是要我们从\(y\)这个位置开始跳,每次跳\(x\)步,然后把每次跳到的数的和加起来就是最终的答案我们发现当\(x\)比较大的时候是可以暴力的,但是比较小的时候就不行了这时就有一个套路了,我们找出一个分界点,比这个分界点大的时候我们暴力否则使用其他方法那么......
  • 深入浅出一致性哈希
    哈希是什么哈希又称散列,是一种计算数据指纹的方法。哈希函数把消息或数据压缩成摘要,使得数据量变小,将数据的格式固定下来业务场景常见的业务场景;网站用户请求后,为了性能一般都会加一层缓存。缓存有多个节点,每个节点存储了不同数据。获取数据,先根据数据取模(哈希)找到缓存节点......
  • 哈希集合、哈希表的拉链法实现
    哈希表705.设计哈希集合//拉链法structListNode{intval;structListNode*next;};typedefstruct{structListNode*data;}MyHashSet;//模constinthashSize=1009;MyHashSet*myHashSetCreate(){MyHashSet*myHashSet=(MyHashSet......