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;
	}
}
相关推荐
纪元A梦1 天前
贪心算法应用:配送路径优化问题详解
算法·贪心算法
C_player_0011 天前
——贪心算法——
c++·算法·贪心算法
kyle~1 天前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Boop_wu1 天前
[数据结构] 队列 (Queue)
java·jvm·算法
hn小菜鸡1 天前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
ゞ 正在缓冲99%…1 天前
leetcode101.对称二叉树
算法
YuTaoShao1 天前
【LeetCode 每日一题】3000. 对角线最长的矩形的面积
算法·leetcode·职场和发展
2zcode1 天前
基于Matlab可见光通信系统中OOK调制的误码率性能建模与分析
算法·matlab·php
纵有疾風起1 天前
数据结构中的排序秘籍:从基础到进阶的全面解析
c语言·数据结构·算法·排序算法
纪元A梦1 天前
贪心算法应用:推荐冷启动问题详解
算法·贪心算法