class Solution {
public boolean isAnagram(String s, String t) {
int len1=s.length();
int len2=t.length();
if(len1!=len2){
return false;
}
HashMap<Character,Integer>dic=new HashMap<>();
for(int i=0;i<len1;i++){
dic.put(s.charAt(i),dic.getOrDefault(s.charAt(i),0)+1);
}
for(int i=0;i<len2;i++){
dic.put(t.charAt(i),dic.getOrDefault(t.charAt(i),0)-1);
}
for(int val:dic.values()){
if(val!=0)
return false;
}
return true;
}
}
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer>set1=new HashSet<Integer>();
Set<Integer>set2=new HashSet<Integer>();
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;
}
}
class Solution {
public boolean isHappy(int n) {
Set<Integer> re = new HashSet<>();
while (n != 1 && !re.contains(n)) {
re.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;
}
}
你不是真正的快乐~
暴力法
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}//两个for走天下
return new int[0];
}
}
哈希法
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> table = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (table.containsKey(target - nums[i])) {
return new int[]{table.get(target - nums[i]), i};
}
table.put(nums[i], i);
}
return new int[0];
}
}