1.有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
int []res = new int[26];
for(int i=0;i<s.length();i++){
res[s.charAt(i)-'a']++;
}
for(int i=0;i<t.length();i++){
res[t.charAt(i)-'a']--;
if(res[t.charAt(i)-'a']<0) return false;
}
return true;
}
}
2.两数组交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer,Integer> hashMap = new HashMap<>();
boolean flag = false;
for(int x:nums1){
if(!hashMap.containsKey(x)) hashMap.put(x,1);
else hashMap.put(x,hashMap.get(x)+1);
}
List<Integer>list = new LinkedList<>();
for(int x:nums2){
if(hashMap.containsKey(x)) {
list.add(x);
flag = true;
}
}
Set<Integer>set = new HashSet<>(list);
if(flag==false) return new int[0];
return set.stream().mapToInt(i -> i).toArray();
}
}
3.快乐数
class Solution {
public int getNext(int n) {
int sum = 0;
while (n != 0) {
int res = n % 10;
sum += res * res;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while (n != 1 && set.contains(n)==false) {
set.add(n);
n = getNext(n);
}
if (n != 1)
return false;
return true;
}
}
4.两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer>map = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(!map.containsKey(nums[i])) map.put(nums[i],i);
}
for(int i=0;i<nums.length;i++){
int x = nums[i];
if(map.containsKey(target-x)&&map.get(target-x)!=i){
return new int[]{i,map.get(target-x)};
}
}
return null;
}
}
5.四数相加
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int res = 0;
Map<Integer,Integer>map = new HashMap<>();
for(int x:nums1){
for(int y:nums2){
map.put(x+y,map.getOrDefault(x+y,0)+1);
}
}
for(int x:nums3){
for (int y:nums4){
if(map.containsKey(0-x-y)) res+=map.getOrDefault(0-x-y,0);
}
}
return res;
}
}
6.三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>>res = new LinkedList<>();
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
if(nums[i]>0) break;
if(i>0&&nums[i]==nums[i-1]) continue;
int l = i+1,r = nums.length-1;
while (l<r){
int sum = nums[l]+nums[r]+nums[i];
if(sum<0){
l++;
}else if(sum>0){
r--;
}else {
res.add(new LinkedList<>(Arrays.asList(nums[l],nums[r],nums[i])));
l++;
r--;
while(nums[l]==nums[l-1]&&l<r) l++;
while (nums[r]==nums[r+1]&&l<r) r--;
}
}
}
return res;
}
}