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

242. 有效的字母异位词
https://leetcode.cn/problems/valid-anagram/description/

public boolean isAnagram(String s, String t) {
        char[] sChar = s.toCharArray();
        char[] tChar = t.toCharArray();
        Arrays.sort(sChar);
        Arrays.sort(tChar);
        if (Arrays.equals(sChar,tChar)){
            return true;
        }else {
            return false;
        }
    }

总结:两个思路:1、字符串转成char数组之后排序,如果排序后一样,则为字母异位词。2、维护一个26大小的数组用来存每个字母出现的数量,若两个字符串字母出现的数量一致,则为字母异位词
349. 两个数组的交集
https://leetcode.cn/problems/intersection-of-two-arrays/description/

HashSet<Integer> set = new HashSet<>();
        HashSet<Integer> res = new HashSet<>();
        for (int i : nums1) {
            set.add(i);
        }
        for (int i : nums2) {
            if (set.contains(i)){
                res.add(i);
            }
        }
        return res.stream().mapToInt(value -> value).toArray();

总结:很简单的hash法
202. 快乐数
https://leetcode.cn/problems/happy-number/description/

public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        while (n != 1 && !set.contains(n)){
            set.add(n);
            n = getNextNumber(n);
        }
        return n == 1;
    }

    private int getNextNumber(int n) {
        int res = 0;
        while (n > 0){
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }

总结:简单题
1. 两数之和
https://leetcode.cn/problems/two-sum/description/

public int[] twoSum(int[] nums, int target) {
        HashMap<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])};
            }else {
                map.put(nums[i],i);
            }
        }
        return new int[1];
    }

总结:当要用在一个数组里找存不存在一个值的时候就要想到hash法

posted @   jeasonGo  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示