242. Valid Anagram
- 思路
- Map
- key为字母
- value为出现次数
- 先遍历一遍s, 加Map
- 再遍历一遍t, check一下,如果有value
- Map
-
java class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()){ return false; } Map map = new HashMap<>(); for (int i = 0; i < s.length(); i++){ map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1 ); } for (char c : t.toCharArray()){ if(!map.containsKey(c)){ return false; } map.put(c, map.get(c) - 1); if (map.get(c) < 0){ return false; } } return true; } }
349. Intersection of Two Arrays
- 思路
- 两个set
- set1记录nums1 集合
- set2记录nums2与set1之间的重复数
- 输出set2
-
java class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set set1 = new HashSet<>(); Set set2 = new HashSet<>(); for(int i : nums1){ set1.add(i); } for(int i : nums2){ if(set1.contains(i)){ set2.add(i); } } int index = 0; int[] res = new int[set2.size()]; for(int i : set2){ res[index++] = i; } return res; } }
- 两个set
202. Happy Number
- 思路
- Set去重
- 主要是套了一个各个digit的平方和的壳子
-
java //这个是自己做的版本,helper输出的各个digit组成的list,可以进一步输出平方和 class Solution { public boolean isHappy(int n) { Set set = new HashSet<>(); while( !set.contains(n) ){ set.add(n); ArrayList list = helper(n); int sum = 0; for(int i : list){ sum += i*i; } if(sum == 1){ return true; } n = sum; } return false; } private ArrayList helper(int n) { ArrayList list= new ArrayList<>(); while ( n != 0){ int digit = n % 10; list.add(digit); n /= 10; } return list; } }
1. Two Sum
- HashMap
-
java //创建HashMap HashMap map = new HashMap(); //遍历 for(int i = 0; i < nums.length; i++){ //如果找到两个数,则return if(map.containsKey(target - nums[i])){ return new int []{i, map.get(target-nums[i])}; } //找不到,则放到map里 map.put(nums[i], i); } return null; //Time Complexity On //Space Complexity On
-