算法训练Day06 | 242. 有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和
我新建的个人博客,欢迎访问:hmilzy.github.io
242. 有效的字母异位词
题目链接: 有效的字母异位词
我自己想到的方法是,用HashMap,先遍历第一个字符串,字符存在key,个数存在value。然后遍历第二个字符串,每来一个字符,就把对应的value减一。如果最后个数小于0的话,就返回false。当然,在程序最开始的地方需要判断两个字符串长度是否相等,如果不相等,直接返回false。
class Solution {
public boolean isAnagram(String s, String t) {
//用的hashmap,效率不太理想
if(s.length() != t.length()){
return false;
}
Map<Character,Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0) + 1);
}
for(int i = 0; i < t.length(); i++) {
if(!map.containsKey(t.charAt(i))) {
return false;
}
map.put(t.charAt(i),map.get(t.charAt(i)) - 1);
if(map.get(t.charAt(i)) < 0){
return false;
}
}
return true;
}
}
第二种方法:直接用长度为26的数组保存字母个数,每个字符对应的位置为s.charAt(i) - ‘a’。这样效率比较高。也是在最后判断数组里的元素值是否为零。
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
table[t.charAt(i) - 'a']--;
}
for(int count : table){
if(count != 0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
题目链接: 两个数组的交集
HashSet
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// 用于存放nums1数组的不重复的所有数字
HashSet<Integer> set = new HashSet<>();
// 遍历添加到set
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
// 用于存放交集的数字
HashSet<Integer> list = new HashSet<>();
for (int i = 0; i < nums2.length; i++) {
// 如果包含就添加到set中去
if (set.contains(nums2[i])) {
list.add(nums2[i]);
}
}
// 方法一: 用JDK8Stream流新特性,不过耗时会更长
// return list.stream().mapToInt(x->x).toArray();
// 方法二: 用数组自己再次遍历添加,迭代器遍历HashSet (推荐)
int[] result = new int[list.size()];
int i = 0;
for (Integer integer : list) {
result[i++] = integer;
}
return result;
}
}
202. 快乐数
题目链接: 快乐数
主要是要了解怎么得到每一位数的平方和
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getNextNumber(n);
}
if(n == 1){
return true;
}
return false;
}
private int getNextNumber(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
1. 两数之和
题目链接: 两数之和
HashMap
key:nums[i]
value:i
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(target - nums[i])){
return new int[]{i,map.get(target - nums[i])};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("no soulution");
}
}