今天的题目比较简单,主要是了解了哈希表的理论基础,以及Java中Hash集合框架的使用
242.有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
int[] arr = new int[26];
for (int i = 0; i < s.length(); i++)
arr[s.charAt(i) - 'a']++;
for (int j = 0; j < t.length(); j++)
arr[t.charAt(j) - 'a']--;
for (int k = 0; k < arr.length; k++)
if (arr[k] != 0)
return false;
return true;
}
}
349. 两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
for (int i : nums1) {
set.add(i);
}
for (int i : nums2) {
if (set.contains(i)) {
resSet.add(i);
}
}
return resSet.stream().mapToInt(x -> x).toArray();
}
}
202. 快乐数
class Solution {
private int getSum(int n) {
int res = 0;
while (n > 0) {
int tmp = n % 10;
res += tmp * tmp;
n /= 10;
}
return res;
}
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (n != 1 && !set.contains(n)) {
set.add(n);
n = getSum(n);
}
return n == 1;
}
}
1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if (nums == null || nums.length == 0) {
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int tmp = target - nums[i];
if (map.containsKey(tmp)) {
res[1] = i;
res[0] = map.get(tmp);
break;
}
map.put(nums[i], i);
}
return res;
}
}