242.有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
int[] hush=new int[26];//用数组形式。默认值为0
for(int i=0;i<s.length();i++)
hush[s.charAt(i)-'a']++;//将s中的字符映射到hush中。如果是a-a的为hush【0】=1;再次遇到字符串a,则hush【0】=2,依次类推,计算该字符出现的次数
for(int i=0;i<t.length();i++)
hush[t.charAt(i)-'a']--;//遇到一个hush【0】则hush【0】-1;减去t字符串中出现的字符的频率
for(int i=0;i<26;i++){
if(hush[i]!=0)//hush中某字符出现的频率非0,说明出现了两个字符串都没有的符号。,则为异位词
return false;
}
return true;
}
}
349 两个数组的交集
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length==0||nums1==null||nums2.length==0||nums2==null){
return new int[0];
}
Set<Integer> resSet=new HashSet<>();//存结果
Set<Integer> set1=new HashSet<>();//将nums1放入set1中
for(int i : nums1){
set1.add(i);
}
for(int i : nums2){
if(set1.contains(i))
resSet.add(i);
}
//将结果存放在数组
int[] arr=new int[resSet.size()];
int j=0;
for(int i:resSet){
arr[j++]=i;
}
return arr;
}
}
202.快乐数
import java.util.Set;
import java.util.HashSet;
class Solution {
public boolean isHappy(int n) {
Set<Integer> record=new HashSet<>();
while(n!=1&&!record.contains(n)){
//n既sum为1或者record中已经包含了这个值,重复了(已经循环过这个sum不是快乐数),则跳出循环
record.add(n);
n=GetNextNum(n);
}
return n==1;
}
private int GetNextNum(int n){
int res=0;
while(n>0){
int temp=n%10;//取末尾数字
res+=temp*temp;
n=n/10;//去除末尾数字
}
return res;
}
}
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);
break;
}
map.put(nums[i],i);
}
return res;
}
}