数据结构哈希表总结
349. 两个数组的交集
力扣题目链接(opens new window)
题意:给定两个数组,编写一个函数来计算它们的交集。
说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。
public int[] intersection(int[] nums1, int[] nums2) {Map<Integer,Integer> map = new HashMap<>(nums1.length);Set<Integer> rs = new HashSet<>(nums2.length);for(int i = 0; i < nums1.length; i++){map.put(nums1[i],1);}for(int j = 0; j < nums2.length; j++){if(map.containsKey(nums2[j])){rs.add(nums2[j]);}}int [] res = new int [rs.size()];int j = 0;Iterator<Integer> iterator = rs.iterator();while(iterator.hasNext()){res[j++] = iterator.next();}return res;
}
这道题不用拆分每个位的数值是多少,先存后计算浪费时间,直接拆分取模计算结果。
第202题. 快乐数
力扣题目链接(opens new window)
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
示例:
输入:19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
public boolean isHappy(int n) {Map<Integer,Integer> map = new HashMap<>();if(n == 1){return true;}int total = n;map.put(total, 1);while (total != 1) {total = getNextNumber(total);if(map.containsKey(total)){return false;}map.put(total, 1);}return true;
}
public int getNextNumber(int n){int sum = 0;while(n >= 10){int num = n % 10;sum+= num * num;n = n /10;}sum += n*n;return sum;
}
这道题的关键是哪个无限循环的意思是拆分后的数字平方和的sum,来回出现
242.有效的字母异位词
力扣题目链接(opens new window)
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1: 输入: s = "anagram", t = "nagaram" 输出: true
示例 2: 输入: s = "rat", t = "car" 输出: false
说明: 你可以假设字符串只包含小写字母。
public boolean isAnagram(String s, String t) {if(s.length() != t.length() || s.equals(t)){return false;}int[] record = new int[26];for (int i = 0; i < s.length(); i++) {record[s.charAt(i) - 'a']++; // 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了}for (int i = 0; i < t.length(); i++) {record[t.charAt(i) - 'a']--;}for (int count: record) {if (count != 0) { // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。return false;}}return true;
}
这道题的技巧是用数组值 - 'a' 作为下标 然后record第一个加,第二个减少,通过判断最终record 各位的值是否为0。
Map<String, Long> countMap = Arrays.asList(s1.split("")).stream().flatMap(s -> Arrays.stream(s.split(""))).filter(s -> !s.trim().isEmpty()).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));for (String key : countMap.keySet()) {System.out.println("key is " + key + " value is:" + countMap.get(key));}List<Persion> persons = new ArrayList<>();Persion persion = new Persion("aaa",1);Persion persion2 = new Persion("aaa",2);Persion persion3 = new Persion("bbb",3);persons.add(persion3);persons.add(persion2);persons.add(persion);persons.stream().sorted(new Comparator<Persion>() {@Overridepublic int compare(Persion o1, Persion o2) {if(o1.getName().compareTo(o2.getName()) == 0){return o2.getAge() - o2.getAge();}else {return o1.getName().compareTo(o2.getName());}}});for(Persion p: persons){System.out.println(p);}