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

242.有效的字母异位词

题目链接:242.有效的字母异位词

解法:1.暴力解法、2.哈希表数组

思路:通过将s[i]-'a'处元素做+1操作统计该处字符出现次数,将其与t字符串各处元素进行对比,做-1操作,当统计出record数组中有不为0的数后返回false。

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] record = new int[26];
        //charAt()方法用于返回指定索引处的字符
        for(int i = 0;i<=s.length()-1;i++){
            record[s.charAt(i)-'a']++;
        }
        for(int i = 0;i<=t.length()-1;i++){
            record[t.charAt(i)-'a']--;
        }
        //增强for循环
        for(int count:record){
            if(count!=0){
                return false;
            }
        }
        return true;
    }
}

349.两个数组的交集

题目链接:349.两个数组的交集

解法:HashSet(数据量小可用)

思路:将nums1中元素存储到set1中,遍历nums2判断哈希表中是否存在该元素,将存在元素存入

set2,将set2中的元素存放到新的数组中。

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for(int i : nums1){
            set1.add(i);
        }
        for(int i : nums2){
            if(set1.contains(i)){
                set2.add(i);
            }
        }
        int[] arr = new int[set2.size()];
        int j = 0;
        for(int i : set2){
            arr[j++] = i;
        }
        return arr;
    }
}

202. 快乐数

题目链接:202. 快乐数

解法:HashSet

思路:使用哈希法判断sum是否重复出现在集合中。当while循环满足n=1或者sum出现在集合中时退出while循环,否则的话将sum存入record,继续求sum。

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while(n !=1&& !record.contains(n)){
            record.add(n);
            n = judgeHappy(n);
        }
        return n == 1;
    }

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

1.两数之和

题目链接:1.两数之和

解法:HashMap(map用于存放访问过的元素,其中key存放判断元素,value存放返回下标)

思路:当需要查询一个元素是否出现过,或者一个元素是否在集合里的时候,就要想到哈希法。通过遍历nums,在map中寻找是否有匹配的key,如果没有匹配的key,将访问过的元素和下标加入到map中去,继续循环直到找到匹配的key。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map<Integer,Integer> map = new HashMap();
        for(int i = 0;i<=nums.length-1;i++){
            int temp = target-nums[i];
            if(map.containsKey(temp)){
                res[1] = i;
                res[0] = map.get(temp);
                break;
            }
            map.put(nums[i],i);
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值