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

242.有效的字母异位词

使用数组模拟哈希表:

  1. 采用foreach效率会更高一点。
  2. 数组命名:采用record/hash更具有描述性。
class Solution {
    public boolean isAnagram(String s, String t) {
        // 边缘条件
        if (s.length()!=t.length()) return false;

        int[] arr = new int[26];
        for(int i=0; i<s.length(); i++){
            arr[s.charAt(i) - 'a']++;
            arr[t.charAt(i) - 'a']--;
        }
        for(int i=0; i<26; i++){
            if (arr[i]!=0) return false;
        }
        return true;
    }
}

349. 两个数组的交集

检查record[n]是否为0

  1. 避免遍历数组。
  2. 去重。

采用stream API,能够简单地转换为数组。
而直接toArray()返回的是对象,所以要先转换为int

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int[] record = new int[1001];
        List<Integer> res = new ArrayList<>();
        for(int n: nums1){
            record[n]++;
        }
        for(int n: nums2){
            if(record[n]!=0){
                res.add(n);
                record[n] = 0;
            } 
        }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }
}

202. 快乐数

  1. 循环判断:n>0
  2. 写的有点乱,不如随想录有条理。
class Solution {
    public boolean isHappy(int n) {
        Set<Integer> hash = new HashSet<>();

        while(true){
            int temp = 0, res = 0;
            while(n>0){
                temp = n % 10;
                res += temp*temp;
                n = n/10;
            }

            if(res==1) return true;
            else if(hash.contains(res)) return false;
            else hash.add(res);

            n = res;
        }
    }
}

随想录解法:

  1. 用private方法来求快乐数。
  2. 判断条件放在while()里,而非while(true)。
class Solution {
    public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while (n != 1 && !record.contains(n)) {
            record.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. 两数之和

  1. 命名:int balance = target - nums[i];
  2. 及时构造数组:return new int []{i, indexMap.get(balance)};
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hash = new HashMap<>();
        int[] res = new int[2];

        for(int i=0; i<nums.length; i++){
            if(hash.containsKey(target-nums[i])){
                res[0] = hash.get(target-nums[i]);
                res[1] = i;
                return res;
            }else{
                hash.put(nums[i], i);
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值