Leetcode 242 有效的字母异位词
题目链接:242. 有效的字母异位词 - 力扣(LeetCode)
//哈希表做法
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) return false;
HashMap<Character,Integer> map = new HashMap<>();
//记录一个字符串里的字符个数
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for(int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
Integer count = map.get(ch);
if(count == null) {
return false;
} else if(count > 1) {
map.put(ch, count - 1);
} else {
map.remove(ch);
}
}
//如果个数和种类相同,哈希表最后为空
return map.isEmpty();
}
}
//字符串排序
class Solution {
public boolean isAnagram(String s, String t) {
char[] chs1 = s.toCharArray();
char[] chs2 = t.toCharArray();
Arrays.sort(chs1);
Arrays.sort(chs2);
return new String(chs1).equals(new String(chs2));
}
}
Leetcode 349 两个数组的交集
题目链接:两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] ret = new int[1010];
HashMap<Integer, Integer> map = new HashMap<>();
HashMap<Integer, Integer> map1 = new HashMap<>();
for(int i = 0; i < nums1.length; i++) {
if(!map.containsKey(nums1[i])) {
map.put(nums1[i],i);
}
}
for (int i = 0; i < nums2.length; i++) {
if(map.containsKey(nums2[i]) && !map1.containsKey(nums2[i])) {
map1.put(nums2[i],i);
}
}
int len = map1.size();
int[] ans = new int[len];
int j = 0;
for (Integer i : map1.keySet()) {
ans[j++] = i;
}
return ans;
}
}
Leetcode 202 快乐数
题目链接:快乐数
class Solution {
public boolean isHappy(int n) {
int fast = get(n) , slow = n;
while(fast != slow) {
fast = get(get(fast));
slow = get(slow);
}
return fast == 1;
}
//计算各位数的平方之和
int get(int n) {
int res = 0;
while(n > 0) {
res += (n % 10) *(n % 10);
n /= 10;
}
return res;
}
}
ps:快乐数这里注意审题!!!
Leetcode 1 两数之和
题目链接:两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
map.put(nums[i],i);
}
for(int i = 0; i < nums.length; i++) {
int j = target - nums[i];
if(map.containsKey(j) && map.get(j) != i) {
arr[0] = i;
arr[1] = map.get(j);
break;
}
}
return arr;
}
}