代码随想录算法训练营第六天| LeetCode242 有效的字母异位词 、LeetCode349 两个数组的交集、LeetCode202 快乐数 、LeetCode1 两数之和

LeetCode242 有效的字母异位词

题目链接:https://programmercarl.com/0242.%E6%9C%89%E6%95%88%E7%9A%84%E5%AD%97%E6%AF%8D%E5%BC%82%E4%BD%8D%E8%AF%8D.html代码:

public class code242 {
    public boolean isAnagram(String s, String t) {

        // 定义一个数组用来存储每个字符出现的次数
        int[] store = new int[26];

        for (int i = 0; i < s.length(); i++) {
            store[s.charAt(i) - 'a']++;
        }

        for (int i = 0; i < t.length(); i++) {
            store[t.charAt(i) -'a']--;
        }

        // 遍历store数组,如果元素都是零则返回true
        for (int i = 0; i < store.length; i++) {
            if (store[i] != 0) {
                return false;
            }
        }
        return true;
    }
}

使用哈希数组的原因是数据量是有限的

LeetCode349 两个数组的交集

题目链接:https://programmercarl.com/0349.%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86.html代码:

public class code349 {
    public int[] intersection(int[] nums1, int[] nums2) {

        Set<Integer> num1 = new HashSet<>();
        Set<Integer> res = new HashSet<>();

        // 将nums1中的元素添加到哈希表当中
        for (int i = 0; i < nums1.length; i++) {
            num1.add(nums1[i]);
        }
        // 判断是否有相同元素,有的话添加到结果集合中
        for (int i = 0; i < nums2.length; i++) {
            if (num1.contains(nums2[i])) {
                res.add(nums2[i]);
            }
        }
        int[] res1 = new int[res.size()];
        int j = 0;
        for (Integer i : res) {
            res1[j++] = i;
        }
        return res1;
    }

使用HashSet,不要忘了函数的返回值是数组,最后将集合转为数组

LeetCode202 快乐数

题目链接:https://programmercarl.com/0202.%E5%BF%AB%E4%B9%90%E6%95%B0.html

代码:

public class code202 {
    public boolean isHappy(int n) {

        Set<Integer> res = new HashSet<>();
        while (n != 1 && !res.contains(n)) {
            res.add(n);
            n = getNextNumber(n);
        }
        return n == 1;
    }

    // 获取计算后的下一个结果
    private int getNextNumber(int n) {

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

跟上一题类似,只不过这道题先写一个函数用来获取下一个num的值

LeetCode1 两数之和

题目链接:https://programmercarl.com/0001.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.html

代码:

public class code1 {
    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[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}

使用HashMap存储键值对,要搞清楚键和值分别对应什么

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值