242.有效的字母异位词
题目链接: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 i=0;i<t.length();i++){
record[t.charAt(i)-'a']--;
}
for(int i:record){
if(i!=0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
题目链接: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> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
//遍历数组1
for(int i:nums1){
set1.add(i);
}
//遍历数组2,判断哈希表中是否存在该元素
for(int i:nums2){
if(set1.contains(i)){
set2.add(i);
}
}
//方法1:将结果集合转为数组
// return set2.stream().mapToInt(x->x).toArray();
//方法2:另外申请一个数组存放set2中的元素,最后返回数组
int[] result = new int[set2.size()];
int j=0;
for(int i:set2){
result[j]=i;
j++;
}
return result;
}
}
202. 快乐数
题目链接:202. 快乐数
- 题目中说了会无限循环,那么也就是说求和的过程中,sum会重复出现,这对解题很重要!
- 熟悉对数值各个位求平方和
class Solution {
public boolean isHappy(int n) {
Set<Integer> result = new HashSet<>();
while(n!=1&& !result.contains(n)){
result.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;
}
}
1. 两数之和
题目链接:1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
//我就需要一个集合来存放我们遍历过的元素,
//然后在遍历数组的时候去询问这个集合,某元素是否遍历过,
//也就是是否出现在这个集合。
//那么我们就应该想到使用哈希法了。
//本题,我们不仅要知道元素有没有遍历过,
//还要知道这个元素对应的下标,
//需要使用 key value结构来存放,key来存元素,value来存下标,
//那么使用map正合适。
int result[] = new int[2];
if(nums==null||nums.length==0){
return result;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<nums.length;i++){
//遍历当前元素,并在map中寻找是否有匹配的key
int temp = target-nums[i];
if(map.containsKey(temp)){
result[1]=i;
result[0]=map.get(temp);
break;
}
// 如果没找到匹配对,就把访问过的元素和下标加入到map中
map.put(nums[i],i);
}
return result;
}
}