C#文件读取
2025/12/25 2:09:51
Set<String> set = new HashSet<>(); set.add("apple"); // 添加元素 set.contains("apple"); // 判断是否存在 set.remove("apple"); // 删除元素 set.size(); // 获取大小 set.isEmpty(); // 判断是否为空 set.clear(); // 清空Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); // 添加/更新 map.get("apple"); // 获取值 map.containsKey("apple"); // 判断key是否存在 map.remove("apple"); // 删除 map.size(); // 获取大小 map.keySet(); // 获取所有key map.values(); // 获取所有value map.entrySet(); // 获取所有键值对//去重 Set<Integer>set=new HashSet<>(); for(int num:arr){ set.add(num); //自动去重 } //检测链表环 Set<ListNode>visited =new HashSet<>(); while(node!=null){ if(visited.contains(node)){ return true; } visited.add(node); node=node.next; }//计数 Map<String,Integer> count=new HashMap(); for(String word:words){ count.put(word,getOrDefault(word,0)+1); }关键方法:
执行过程:
words = ["apple", "banana", "apple"]
第1次:apple
getOrDefault("apple", 0) = 0(不存在)
put("apple", 0 + 1) → count = {apple=1}第2次:banana
getOrDefault("banana", 0) = 0
put("banana", 0 + 1) → count = {apple=1, banana=1}第3次:apple
getOrDefault("apple", 0) = 1(已存在)
put("apple", 1 + 1) → count = {apple=2, banana=1}
public int[] towSum(int[]nums,int target){ Map<Integer,Integer>map=new HashMap<>(); for(int i=0;i<nums.length;i++){ int need=target-nums[i]; } if(map.containKey(need)){ int index1=map.get(need); //之前遇到的数的索引 int index2=i; //当前数的索引 int [] result=new int[2]; result[0]=index1; result[1]=index2; return result; } //没找到,把当前数和索引存入map map.put(nums[i],i); }| 特性 | HashSet | HashMap |
|---|---|---|
| 存储内容 | 值(元素) | 键值对 |
| 重复性 | 不允许重复 | key 不允许重复 |
| 时间复杂度 | O(1) 平均 | O(1) 平均 |
| 主要用途 | 去重、查找 | 映射、计数 |
| 常用方法 | add, contains, remove | put, get, containsKey |