力扣202题、349题、1题、牛客92(哈希表)
202、快乐数
基本思想:
题目是中说如果平方和变不到1的话可能会无限循环
说明求和过程中,和 会重复出现
判断一个元素是否出现在集合里的时候,就要考虑哈希表
具体实现:
只要record中要加入的数重复出现一次就退出循环,得出不是快乐数的结论
代码:
class Solution { public boolean isHappy(int n) { Set<Integer> record = new HashSet<>(); while (n != 1 && !record.contains(n)) { record.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; } }
349、两个数组的交集
基本思想:
输出每一个元素一定是唯一的,也就是说输出的结果去重,可以不考虑输出结果的顺序
所以要使用HashSet
使用数组来做哈希的题目,是因为题目都限制了数值的大小。
而这道题目没有限制数值的大小,就无法使用数组来做哈希表了。
具体实现:

代码:
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> set1 = new HashSet<>(); Set<Integer> resSet = new HashSet<>(); for (int i : nums1){ set1.add(i); } for (int i : nums2){ if (set1.contains(i)){ resSet.add(i); } } int[] resArr = new int[resSet.size()]; int index = 0; for (int i : resSet){ resArr[index++] = i; } return resArr; } }
1、两数之和
基本思想:
HashMap
具体实现:
nums = [2,7,11,15]
下标: 0,1, 2, 3 target =9
定义一个HashMap,map<数值,下标>
循环遍历数组:
i = 0时,9-nums[0] = 7,寻找target - nums[i]是否在map中
7不在map中,所以把nums[0]和下标0放入map中 map = [(2,0)]
i = 1时,9-nums[1] = 2,寻找target - nums[i]是否在map中
2在map中,所以得到2和7的下标0和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 temp = target - nums[i]; if(map.containsKey(temp)){ res[1] = i; res[0] = map.get(temp); } map.put(nums[i],i); } return res; } }
牛客92.最长无重复子数组
map(数组元素的值,数组元素的位置)
map中包含遍历元素的值说明有重复,j是 重复的元素的上一个位置+1,j的位置比重复的元素的上一个位置+1大就保持不变
public int maxLength(int[] arr) {
if (arr.length == 0)
return 0;
HashMap<Integer, Integer> map = new HashMap<>();
int max = 0;
for (int i = 0, j = 0; i < arr.length; ++i) {
if (map.containsKey(arr[i])) {
j = Math.max(j, map.get(arr[i]) + 1);
}
map.put(arr[i], i);
max = Math.max(max, i - j + 1);
}
return max;
}
import java.util.*; public class Solution { public int maxLength(int[] arr) { //用链表实现队列,队列是先进先出的 Queue<Integer> queue = new LinkedList<>(); int res = 0; for (int c : arr) { while (queue.contains(c)) { //如果有重复的,队头出队 queue.poll(); } //添加到队尾 queue.add(c); res = Math.max(res, queue.size()); } return res; } }
浙公网安备 33010602011771号