代码随想录算法训练营第六天| 242. 有效的字母异位词 349. 两个数组的交集 202. 快乐数 1. 两数之和
242. 有效的字母异位词
https://leetcode.cn/problems/valid-anagram/description/

public boolean isAnagram(String s, String t) {
char[] sChar = s.toCharArray();
char[] tChar = t.toCharArray();
Arrays.sort(sChar);
Arrays.sort(tChar);
if (Arrays.equals(sChar,tChar)){
return true;
}else {
return false;
}
}
总结:两个思路:1、字符串转成char数组之后排序,如果排序后一样,则为字母异位词。2、维护一个26大小的数组用来存每个字母出现的数量,若两个字符串字母出现的数量一致,则为字母异位词
349. 两个数组的交集
https://leetcode.cn/problems/intersection-of-two-arrays/description/

HashSet<Integer> set = new HashSet<>();
HashSet<Integer> res = new HashSet<>();
for (int i : nums1) {
set.add(i);
}
for (int i : nums2) {
if (set.contains(i)){
res.add(i);
}
}
return res.stream().mapToInt(value -> value).toArray();
总结:很简单的hash法
202. 快乐数
https://leetcode.cn/problems/happy-number/description/

public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while (n != 1 && !set.contains(n)){
set.add(n);
n = getNextNumber(n);
}
return n == 1;
}
private int getNextNumber(int n) {
int res = 0;
while (n > 0){
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
总结:简单题
1. 两数之和
https://leetcode.cn/problems/two-sum/description/

public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])){
return new int[]{i,map.get(target - nums[i])};
}else {
map.put(nums[i],i);
}
}
return new int[1];
}
总结:当要用在一个数组里找存不存在一个值的时候就要想到hash法
浙公网安备 33010602011771号