【Java数据结构】Map和Set(哈希表详解)

Map和set是一种专门用来进行搜索的容器或者数据结构,其搜索的效率与其具体的实例化子类有关。

目录

1. Map

实例化

添加元素(put)

打印

2. Set

实例化

添加元素(add)

打印

3.  小练习

3.1 找出重复的数据(Set练习)

3.2 去重(Set练习)

3.3 统计重复数据出现的次数(Map练习)

4. LeetCode题型训练

4.1 只出现一次的数字

4.2 ⭐⭐复制带随机指针的链表

4.3 宝石与石头

4.4 坏键盘打字

4.5 前K个高频单词(难题)


1. Map

Map是一个接口类,该类没有继承自Collection,该类中存储的是结构的键值对,并且K一定是唯一的,不 能重复。

实例化

        Map<String,String> map = new HashMap<>();
        HashMap<String,String> map2 = new HashMap<>();

添加元素(put)

        map.put("猴哥","孙悟空");
        map.put("八戒","猪八戒");
        map.put("悟净","沙僧");

打印

import java.util.Set;
        //1、直接打印法
        System.out.println(map);

        //Set打包后再遍历打印法
        Set<Map.Entry<String,String>> set = map.entrySet();
        for (Map.Entry<String, String> entry : set) {
            System.out.println("key:"+entry.getKey()+" Value:"+entry.getValue());
        }

2. Set

Set是一个集合类。Set与Map主要的不同有两点:Set是继承自Collection的接口类,Set中只存储了Key。

实例化

import java.util.Set;
        Set<Integer> set = new HashSet<>();
        HashSet<Integer> set1 = new HashSet<>();

添加元素(add)

和Map一样也是无序的!

        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);
        System.out.println(set1);
        
        set.add("hello");
        set.add("hello1");
        set.add("hello2");
        set.add("hello3");
        set.add("hello4");
        System.out.println(set);

打印

        //1、直接打印
        System.out.println(set);

        //2、迭代器(不可以遍历Map)
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

3.  小练习

  1. 从10W个数据中,找出第一个重复的数据
  2. 去除10W个数据当中,重复的数据(去重)
  3. 统计重复的数据出现的次数

3.1 找出重复的数据(Set练习)

思路:使用set.contains( ) 判断是否已存在于set中

    //判断是否存在set.contains()
    public static void main(String[] args) {
        int[] array = new int[10];
        Random rand = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = rand.nextInt(10);
        }
        System.out.println(Arrays.toString(array));
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            if (set.contains(array[i])) {
                System.out.println(array[i]);
                break;
            }
            set.add(array[i]);
        }
        System.out.println(set);
    }

3.2 去重(Set练习)

    //判断是否存在set.contains()
    public static void main(String[] args) {
        int[] array = new int[10];
        Random rand = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = rand.nextInt(10);
        }
        System.out.println(Arrays.toString(array));
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            set.add(array[i]);
        }
        System.out.println(set);
    }

3.3 统计重复数据出现的次数(Map练习)

使用map.containsmap.get() == null 都可以用来判断是否已经存在。

public class Test {
    public static void main(String[] args) {
        int[] array = new int[10];
        Random rand = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = rand.nextInt(5);
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        //判断数组的数据 是否再map中 没有就是1,有的话就value+1
        for (int i = 0; i < array.length; i++) {
            /*if (map.containsKey(array[i])) {
                int val = map.get(array[i]);
                map.put(array[i], val+1);
            } else {
                map.put(array[i], 1);
            }*/
            if (map.get(array[i] == null)) {
                map.put(array[i],1);
            } else {
                int val = map.get(array[i]);
                map.put(array[i],val+1);
            }
        }
        //打印
        for (Map.Entry<Integer,Integer> entry: map.entrySet()) {
            System.out.println("关键字 "+entry.getKey()+" 次数"+entry.getValue());
        }
    }
}

4. LeetCode题型训练

4.1 只出现一次的数字

136. 只出现一次的数字 - 力扣(LeetCode) (leetcode-cn.com)

常规最优解题法(异或):

class Solution {
    public int singleNumber(int[] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum ^= nums[i];
        }
        return sum;
    }
}

使用Set:

class Solution {
    public int singleNumber(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        for (int val : nums) {
            if (set.contains(val)) {
                set.remove(val);
            } else {
                set.add(val);
            }
        }
        for (int val : nums) {
            if (set.contains(val)) {
                return val;
            }
        }
        return -1;
    }
}

4.2 ⭐⭐复制带随机指针的链表

138. 复制带随机指针的链表 - 力扣(LeetCode) (leetcode-cn.com)

class Solution {
    public Node copyRandomList(Node head) {
        HashMap<Node,Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            Node node = new Node(cur.val);
            map.put(cur,node);
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}

4.3 宝石与石头

771. 宝石与石头 - 力扣(LeetCode) (leetcode-cn.com)

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        HashSet<Character> set = new HashSet<>();
        for (int i = 0; i < jewels.length(); i++) {
            char ch = jewels.charAt(i);
            set.add(ch);
        }
        int count = 0;
        for (int i = 0; i < stones.length(); i++) {
            char ch = stones.charAt(i);
            if (set.contains(ch)) {
                count++;
            }
        }
        return count;
    }
}

4.4 坏键盘打字

旧键盘 (20)__牛客网 (nowcoder.com)

思路:

  1. 把str1当中的每个字符,转换成大写的,然后放到集合当中(char[ ]  ch=str1.toUpperCase().toCharArray() ;
  2. 遍历str1,每个字符仍然要是大写,和集合当中的元素去比较,没有就输出
import java.util.*;

public class Main {
    public static void func(String str1, String str2) {
        HashSet<Character> set = new HashSet<>();
        //把打印出来的东西放进set
        for (char ch : str2.toUpperCase().toCharArray()) {
            set.add(ch);
        }
        for (char ch : str1.toUpperCase().toCharArray()) {
            if (!set.contains(ch)) {
                System.out.print(ch);
                set.add(ch);
            }
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        String str2 = sc.nextLine();
        func(str1,str2);
    }
}

4.5 前K个高频单词(难题)

692. 前K个高频单词 - 力扣(LeetCode) (leetcode-cn.com)

思路:

  1. 统计字符串当中每个单词出现的次数(HashMap)
  2. 定义一个小根堆,设置其比较方式是根据每个单词出现的次数进行比较
  3. 开始遍历map,拿到每一个entry
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        //1、统计单词出现的次数 存放在map当中
        HashMap<String,Integer> map = new HashMap<>();
        for (String s : words) {
            if (map.get(s) == null) {
                map.put(s,1);
            } else {
                int val = map.get(s);//原来这个单词出现的次数
                map.put(s,val+1);
            }
        }

        //定义一个小根堆,因为我们找的是出现频率高的,所以小根堆的比较方式是根据每个单词出现的次数进行比较
    PriorityQueue<Map.Entry<String,Integer>> minHeap = new PriorityQueue<>(new Comparator<Map.Entry<String,Integer>>() {
        @Override
        public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
            if(o1.getValue().compareTo(o2.getValue()) == 0) {
                return o2.getKey().compareTo(o1.getKey());
            }
            return o1.getValue()-o2.getValue();
        }
    });

        //3、开始遍历map,拿到每一个entry
        for (Map.Entry<String,Integer> entry : map.entrySet()) {
            if (minHeap.size() < k ) {
                minHeap.offer(entry);
            } else {
                Map.Entry<String,Integer> top = minHeap.peek();
                if (top != null) {
                    if (top.getValue().compareTo(entry.getValue()) == 0) {
                        if (entry.getKey().compareTo(top.getKey()) < 0) {
                            minHeap.poll();
                            minHeap.offer(entry);
                        }
                    } else {
                        if (entry.getValue().compareTo(top.getValue()) > 0) {
                            minHeap.poll();
                            minHeap.offer(entry);
                        }
                    }
                }
            }
        }

        //4、小堆弹出信息
        List<String> ret = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            Map.Entry<String,Integer> top = minHeap.poll();
            if (top != null) {
                ret.add(top.getKey());
            }
        }
        Collections.reverse(ret);
        return ret;
    }
}

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值