使用數(shù)組來做哈希的題目是因?yàn)轭}目限制數(shù)組大小,如果分散的話不要使用數(shù)組,會(huì)造成極大的空間浪費(fèi)
242.有效的字母異位詞
題目鏈接:242.有效的字母異位詞
暴力法
哈希法 長度26的數(shù)組
349. 兩個(gè)數(shù)組的交集
- 用set解決題目
202. 快樂數(shù)
題目鏈接:202. 快樂數(shù)
- 用哈希集合檢測循環(huán)
1. 兩數(shù)之和
題目鏈接:1. 兩數(shù)之和https://leetcode.cn/problems/happy-number/)
class Solution {
public int[] twoSum(int[] nums, int target) {
int []ans = new int[2];
Map<Integer, Integer> hashtable = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(hashtable.containsKey(temp)){
ans[0] = hashtable.get(temp);
ans[1] = i;
return ans;
}else{
hashtable.put(nums[i], i);
}
}
return ans;
}
}