代码随想录算法训练营第6天 | 242.有效的字母异位词 349. 两个数组的交集 202. 快乐数 1. 两数之和

75 阅读2分钟

242.有效的字母异位词

题目链接/文章讲解/视频讲解: programmercarl.com/0242.%E6%9C…

哈希表(hash table)使用hash函数计算得到的索引(也叫hash code)并能直接访问存储地址。使用哈希法解决问题,通常使用数组、set集合、map映射,来解决。使用数组本质并不是一个标准意义上的哈希表,而是使用哈希思想。本题就是一个使用哈希思想和数组解决问题的例子。

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] arr = new int[26];
        for(int i = 0; i < s.length(); i++)
        {
            arr[s.charAt(i) - 'a']++;
        }
        for(int i = 0; i < t.length(); i++)
        {
            arr[t.charAt(i) - 'a']--;
        }
        for(int i = 0; i < 26; i++)
        {
            if(arr[i] != 0) return false;
        }
        return true;
    }
}

349. 两个数组的交集

建议:本题就开始考虑 什么时候用set 什么时候用数组,本题其实是使用set的好题,但是后来力扣改了题目描述和 测试用例,添加了 0 <= nums1[i], nums2[i] <= 1000 条件,所以使用数组也可以了,不过建议大家忽略这个条件。 尝试去使用set。

题目链接/文章讲解/视频讲解:programmercarl.com/0349.%E4%B8…

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Set<Integer> list = new HashSet<>();
        for(int num : nums1)
        {
            if(!set.contains(num))
            {
                set.add(num);
            }
        }
        for(int num : nums2)
        {
            if(set.contains(num))
            {
                list.add(num);
            }
        }
        int[] res = new int[list.size()];
        int index = 0;
        for(int i : list)
        {
            res[index++] = i;
        }
        return res;
    }
}

202. 快乐数

题目链接/文章讲解:programmercarl.com/0202.%E5%BF…

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while(true){
            n = getNext(n);
            if(n == 1) {
                return true;
            }
            if(set.contains(n)){
                return false;
            }else{
                set.add(n);
            }
        }
    }
    public int getNext(int n){
        int sum = 0;
        while(n != 0){
            sum += (n%10) * (n%10);
            n /= 10;
        }
        return sum;
    }
}

1. 两数之和

题目链接/文章讲解/视频讲解:programmercarl.com/0001.%E4%B8…

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            int div = target - nums[i];
            if(map.containsKey(div)){
                res[1] = i;
                res[0] = map.get(div);
                break;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}