leetcode-05-[242]有效的字母异位词[349]两个数组的交集[202]快乐数[1]两数之和

重点:

哈希表:当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法

常用数据结构:

List 数组 固定大小 如26个字母,10个数字 空间换时间

Set hashset 去重

Map hashmap <K,V>形式

小重点:

注意边界条件

一、242有效的字母异位词

数组

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

二、349两个数组的交集

set

java 复制代码
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        //临界条件
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        HashSet<Integer> set = new HashSet<Integer>();
        HashSet<Integer> resSet = new HashSet<Integer>();
        for(int i:nums1) {
            set.add(i);
        }
        for(int j:nums2){
            if(set.contains(j)){
                resSet.add(j);
            }
        }
        return resSet.stream().mapToInt(i -> i).toArray();
    }
}

三、202快乐数

无限循环:即出现不止一次,考虑用哈希表

java 复制代码
class Solution {
    public boolean isHappy(int n) {
        //无限循环  重点
        //即出现不止一次
        //list 不好处理
        HashSet<Integer> records = new HashSet<>();
        while(n!=1&&!records.contains(n))
        {
            records.add(n);
            n=getNextNumber(n);

        }
        return n==1;
    }
    int getNextNumber(int n){
        int sum=0;
        while(n!=0){
            int tmp=n%10;
            sum+=tmp*tmp;
            n=n/10;
        }
        return sum;
    }

}

四、1两数之和

map

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
		HashMap<Integer, Integer> map = new HashMap<>();
		//注意一下
		int[] res=new int[2];
		//临界条件
		if(nums == null || nums.length == 0){
			return res;
		}
		for(int j=0;j<nums.length;j++){
			if(map.containsKey(target-nums[j])){
				//赋值
				res[0]=j;
				res[1]=map.get(target-nums[j]);
				break;
			}
			//此处可加入map,不用单独的for循环赋值
			map.put(nums[j], j);
		}
		return res;
	}
}
相关推荐
海石39 分钟前
【JS击败90%】前缀和+定长滑动窗口
算法·leetcode
Tisfy1 小时前
LeetCode 2685.统计完全连通分量的数量:DFS求每个连通块的边点数
算法·leetcode·深度优先··题解·连通图·全连通分量
海石1 小时前
1次遍历,空间复杂度击败100%,时间复杂度击败85%
算法·leetcode
L歪歪君2 小时前
Apache Doris全链路性能优化实战指南:从架构设计到生产落地
java·开发语言·算法
m0_466525292 小时前
从“算法内卷”到“可信易用” 东软多模态医学人工智能平台开启无代码科研新时代
人工智能·算法
码少女2 小时前
数据结构——冒泡排序及优化
数据结构·算法·排序算法
梦回江东2 小时前
ansible中的主机清单
算法
青梅橘子皮2 小时前
string---入门OJ题(1)
数据结构·算法
qq_454245033 小时前
BasicMethod.Map 设计框架:8 个并行基础模块的数学根基与实现
数据结构·算法·c#
青山木3 小时前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先