day06

本文介绍了四个Java编程题目,涉及字符串异位词检查、数组交集、快乐数判断和两数之和,展示了使用哈希表、迭代和条件判断解决这些问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

242. 有效的字母异位词

字符串s和t都只包含小写字母,新建一个数组来存储s中每个字符出现的次数,然后遍历t,对应位置上的字符自减。最后遍历新数组,若数组中的每一位都是0,则符合条件。

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

        for (int i = 0; i < result.length; i++) {
            if (result[i] != 0) {
                return false;
            }
        }
        return true;
    }
}

349. 两个数组的交集

使用两个hashset,第一个hashset用来存储nums1的所有元素,然后遍历nums2,同时判断nums2中的元素是否出现在第一个hashset,若出现,则说明当前元素时两个数组的交集,将其放入另一个hashset

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1.length == 0 || nums1 == null || nums2.length == 0 || nums2 == null) {
            return new int[0];
        }
        HashSet<Integer> temp = new HashSet<>();
        HashSet<Integer> result = new HashSet<>();
        for (int i = 0; i < nums2.length; i++) {
            temp.add(nums2[i]);
        }
        for (int i = 0; i < nums1.length; i++) {
            if (temp.contains(nums1[i])) {
                result.add(nums1[i]);
            }
        }
        return result.stream().mapToInt(x -> x).toArray();
    }
}

202. 快乐数

注意条件无限循环,若无限循环返回false,直到找到值1。判断元素是否在集合中出现,使用hash法。

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> result = new HashSet<>();
        while (n != 1 && !result.contains(n)) {
            result.add(n);
            n = getNextInt(n);
        }
        return n == 1;
    }
    private int getNextInt(int n) {
        int res = 0;
        while (n > 0) {
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }
}

1. 两数之和

新建一个hashmap,遍历数组,若map中不存在键为target-nums[i]的元素则将当前数组的值和下标放入map(数组的值做key的原因是简化操作)。若出现符合条件的元素,跳出循环并返回。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] result = new int[2];

        for (int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if (map.containsKey(temp)) {
                result[0] = i;
                result[1] = map.get(temp);
                break;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值