Leetcode: 242 有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
int slen = s.length();
int tlen = t.length();
if(slen != tlen) return false;
HashMap<Character, Integer> smap = new HashMap<Character, Integer>();
for(int i = 0; i < slen; i++){
char c = s.charAt(i);
smap.put(c, smap.getOrDefault(c,0)+1);
}
for(int i = 0; i < tlen; i++){
char c = t.charAt(i);
int times = smap.getOrDefault(c,0);
if(times == 0) return false;
smap.put(c, smap.getOrDefault(c,0)-1);
}
return true;
}
}
LeetCode: 349 两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
ArrayList<Integer> output = new ArrayList<Integer>();
HashSet<Integer> set1 = new HashSet<Integer>();
HashSet<Integer> set2 = new HashSet<Integer>();
for(int a: nums1){
set1.add(a);
}
for(int a:nums2){
set2.add(a);
}
for(Integer i: set2){
boolean flag = set1.remove(i);
if(flag) output.add(i);
}
int[] finaloutput = new int[output.size()];
for(int i = 0; i < output.size(); i++){
finaloutput[i] = output.get(i);
}
return finaloutput;
}
}
LeetCode: 202 快乐数
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> havefind = new HashSet<Integer>();
while(!havefind.contains(n)){
havefind.add(n);
if(n == 1){
return true;
}
System.out.println(n);
n = powersum(n);
}
return false;
}
public int powersum(int n){
int sum = 0;
while(n / 10 != 0){
sum += Math.pow(n % 10, 2);
n /= 10;
}
sum += Math.pow(n, 2);
return sum;
}
}
Leetcode: 1 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> havefind = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> wantfind = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
havefind.put(nums[i], i);
if(wantfind.containsKey(nums[i]))
return new int[]{i, wantfind.get(nums[i])};
wantfind.put(target - nums[i], i);
}
return new int[]{0, 0};
}
}