任务
哈希表基础理论&异位数&数组交集&快乐数&两数之和
哈希表基础理论
哈希表,又称散列表,根据关键键值就能直接访问的数据结构。
主要解决的场景是一个元素是否存在于某个集合中。
242.有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
char[] record = new char[26];
for (int i = 0; i < s.length(); i++) {
record[s.charAt(i) - 'a'] += 1;
}
for (int i = 0; i < t.length(); i++) {
record[t.charAt(i) - 'a'] -= 1;
}
for (int i = 0; i < 26; i++) {
if (record[i] != 0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<Integer>();
Set<Integer> retSet = new HashSet<Integer>();
for (int i : nums1) {
set.add(i);
}
for (int i : nums2) {
if (set.contains(i)) {
retSet.add(i);
}
}
return retSet.stream().mapToInt(x->x).toArray();
}
}
第202题. 快乐数
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
int res = n;
while(true) {
res = calcSum(res);
if (res == 1) {
return true;
}
if (set.contains(res)) {
return false;
}
set.add(res);
}
}
public int calcSum(int n){
int sum = 0;
while (n != 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
}
1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int diff = 0;
for (int i = 0; i < nums.length; i++) {
diff = target - nums[i];
if (map.containsKey(diff)) {
return new int[]{i, map.get(diff)};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
}