每日算法(四)

每日算法(四)

242.有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1: 输入: s = "anagram", t = "nagaram" 输出: true

示例 2: 输入: s = "rat", t = "car" 输出: false

说明: 你可以假设字符串只包含小写字母。

题解

都是小写字母我们使用一个长度为26的数组 比较他们每个字母的数量是否相同即可

int[] record = new int[26];

对两个字符串进行遍历 在数组的每个相对位置进行记录 (一个含有相应的字母就++ 另一个--) 最后进行比较是否为0

class Solution {
    public boolean isAnagram(String s, String t) {
       int[] record = new int[26];

       for (int i = 0; i < s.length(); i++) {
          record[s.charAt(i) - 'a']++;     // 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
       }

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

       for (int count: record) {
          if (count != 0) {               // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
             return false;
          }
       }
       return true;                        // record数组所有元素都为零0,说明字符串s和t是字母异位词
    }
}

349. 两个数组的交集

题意:给定两个数组,编写一个函数来计算它们的交集。

349. 两个数组的交集

说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。

题解

这个我们直接使用set集合进行数据的存放 之后再将集合转换成数组就行了


class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
       if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
          return new int[0];
       }
       Set<Integer> set1 = new HashSet<>();
       Set<Integer> resSet = new HashSet<>();
       //遍历数组1
       for (int i : nums1) {
          set1.add(i);
       }
       //遍历数组2的过程中判断哈希表中是否存在该元素
       for (int i : nums2) {
          if (set1.contains(i)) {
             resSet.add(i);
          }
       }

       //将结果集合转为数组

       return resSet.stream().mapToInt(x -> x).toArray();

    }
}


第202题. 快乐数

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

示例:

输入:19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

题解

这个题上面特意说可能是无限循环重复

所以我们判断当数据出现重复的时候我们返回false就行 我们要记录每次生成的数据

我们还是使用set 进行存储 n != 1 && !record.contains(n) 当这个条件时,我们就把当前的这个数据添加到set集合之中 之后 fan

n == 1即可

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. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

LICENSED UNDER CC BY-NC-SA 4.0