Map和Set小练习

目录

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

2. 去重(Set练习)

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

4. 只出现一次的数字

5. ⭐⭐复制带随机指针的链表

6. 宝石与石头

7. 坏键盘打字

8. 前K个高频单词


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

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. 统计重复数据出现的次数(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. 只出现一次的数字

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

5. ⭐⭐复制带随机指针的链表

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

6. 宝石与石头

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

7. 坏键盘打字

旧键盘 (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);
    }
}

8. 前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;
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值