1
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int[] count = new int[26];
for(int i=0;i<s.length();i++){
count[s.charAt(i)-'a']++;
count[t.charAt(i)-'a']--;
}
for(int c:count){
if(c != 0){
return false;
}
}
return true;
}
}
2.
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 i: nums2){
if(set1.contains(i)){
set2.add(i);
}
}
// int[] arr = new int[set2.size()];
// int j = 0;
// for(int i : set2){
// arr[j++] = i;
// }
// return arr;
return set2.stream().mapToInt(x -> x).toArray();
}
}
3.
class Solution {
public boolean isHappy(int n) {
Set<Integer> store = new HashSet<>();
while(n!=1 && !store.contains(n)){
store.add(n);
n = computeSum(n);
}
return n==1;
}
private int computeSum(int num){
int sum = 0;
while(num>0){
int a = num % 10;
int b = a * a;
sum = sum + b;
num = num / 10;
}
//System.out.println(sum);
return sum;
}
}
4
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
//Hash索引表示 eg.[2,7,11,15] target=9
//2,0
//7,1
//11,2
//15,3 只需遍历一遍数组
//循环法:将两个数字返回数组写法 return new int[]{i, j};
//最终返回空数组 return new int[0];
//本身的含义是长度为0的空数组:返回一个垃圾值,是为了防止编译器报错