242.有效的字母异位词
也可使用26位数组进行字母频率统计 (需要适应这种思路,可以引申到桶排序)
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++){
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < t.length(); i++){
if (!map.containsKey(t.charAt(i))) return false;
if (map.get(t.charAt(i)) == 1) map.remove(t.charAt(i));
else map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
}
return map.size() == 0;
}
349. 两个数组的交集
使用stream()输出最终结果到数组:
return resSet.stream().mapToInt(x -> x).toArray();
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<>();
for (int n: nums1){
set1.add(n);
}
HashSet<Integer> set2 = new HashSet<>();
for (int n: nums2){
set2.add(n);
}
List<Integer> list = new ArrayList<>();
for (int n: set1){
if (set2.contains(n)) {
list.add(n);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < res.length; i++){
res[i] = list.get(i);
}
return res;
}
202. 快乐数
使用循环特征进行Hash Set存储(题目关键信息)
需要注意在每层while loop中n的更新
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while(n != 1){
int sum = getSum(n);
if (!set.add(sum)) return false;
n = sum;
}
return true;
}
private int getSum(int n){
int sum = 0;
while (n != 0){
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
1. 两数之和
典中典,可以结合two sum系列问题
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++){
if (map.containsKey(nums[i])) return new int[]{map.get(nums[i]), i};
map.put(target - nums[i], i);
}
return null;
}