使用场景:当判断一个数据是否出现过时 第一时间想到哈希法
242.有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for(int i = 0; i < s.length();i++){
record[s.charAt(i)-'a']++;
}
for(int j = 0; j < t.length() ; j++){
record[t.charAt(j)-'a']--;
}
for(int c = 0; c<26;c++){
if(record[c] != 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<>();
Set<Integer> intersect = new HashSet<>();
for(int i = 0;i < nums1.length;i++){
set.add(nums1[i]);
}
for (int i = 0;i<nums2.length;i++){
if(set.contains(nums2[i])){
intersect.add(nums2[i]);
}
}
int count = 0;
int[] result = new int[intersect.size()];
for(int num: intersect){
result[count++]=num;
}
return result;
}
}
202.快乐数
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(n!=1){
if(set.contains(n)){
return false;
}
set.add(n);
n = getNext(n);
}
return true ;
}
private int getNext(int n){
int res = 0;
while(n > 0){
int temp = 0;
temp = n%10;
res += temp * temp;
n = n/10;
}
return res;
}
}
注意java运算符优先级,之前写的是 res += n%10 * n%10 因为 *和 %优先级一致,这会导致不符合预期的结果。
1.两数之和
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]; // 遍历当前元素,并在map中寻找是否有匹配的key
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
}
return res;
}