242.有效的字母异位词
思路:由题目可知,所涉及字母都是小写,故由26个字母。设置一个hash数组,用于记录出现字母的次数,先由s字符串开始,记录hash++,然后是t字符串,记录hash--,最后循环26次,判断hash的每个位置是否都为0,如果不是,就返回false即可
代码:
class Solution {
public boolean isAnagram(String s, String t) {
int[] hash=new int[26];
for(int i=0;i<s.length();i++){
hash[s.charAt(i)-'a']++;
}
for(int i=0;i<t.length();i++){
hash[t.charAt(i)-'a']--;
}
for(int i=0;i<26;i++){
if(hash[i]!=0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
思路:运用set进行做题,set可以去除重复元素。设置两个set分别是set1和set2。set1用于存储nums1的元素值,然后遍历nums2,查看nums2中的元素是否在set1中,如果在set1中,则用set2存储。最后set2以数组的形式返回,得到答案。
代码:
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<>();
for(int i:nums1){
set1.add(i);
}
for(int x:nums2){
if(set1.contains(x)){
set2.add(x);
}
}
int[] arr = new int[set2.size()];
int j = 0;
for(int i : set2){
arr[j++] = i;
}
return arr;
}
}
202. 快乐数
思路:用set实现,由题目可以知道,最后n=1时,返回true。!set.contains(n) 用于判断当前的n是否在set中出现过,如果出现过,表示这个输入数n出现了循环现象,之后就没有必要继续执行下去,然后返回false(即n!=1)。否则就是知道n为1为止,退出循环,返回true(即n==1)
代码:
public boolean isHappy(int n) {
Set<Integer> set=new HashSet<>();
while(n!=1 && !set.contains(n)){
set.add(n);
n=judge(n);
}
return n==1;
}
private int judge(int n){
int res=0;
while(n>0){
int temp=n%10;
res+=temp*temp;
n=n/10;
}
return res;
}
1. 两数之和
思路:这道题目用到的是map,map用于存储元素的值和下标,key存储nums中的值,value哟女友存储值对应的下标。为什么是这样存储呢,因为map是提供key寻找的,而我们每次进入循环,得到的temp是 target-当前元素值 得到的,得到的是值,故在查找map时,map的key也只能是值的形式才可以找到。当map中找到了与temp匹配的值,表示有两个数相加等于target,此时用res存储下标,退出循环。返回res即可
代码:
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.containKey(temp)){
res[1]=i;//获取当前元素下标
res[0]=map.get(temp);//获取与之匹配的下标
break;//退出循环
}
map.put(nums[i],i);//当map中没有与temp匹配时,把当前元素加入到map中
}
return res;//最后,返回这个存储下标的数组即可
}
}