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

47 阅读1分钟

day6休息---day6继续继续

 242.有效的字母异位词 

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }

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

题目链接/文章讲解/视频讲解: programmercarl.com/0242.%E6%9C…

 349. 两个数组的交集 

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<>();

        for (int i : nums1)
            set1.add(i);
        for (int i : nums2) {
            if (set1.contains(i)) {
                resSet.add(i);
            }
        }
        // return resSeT.stream().mapToInt(x -> x).toArray;
        int[] arr = new int[resSet.size()];
        int j = 0;
        for (int i : resSet) {
            arr[j++] = i;
        }

        return arr;
    }
}

题目链接/文章讲解/视频讲解:programmercarl.com/0349.%E4%B8…

 202. 快乐数 

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;
    }
}

题目链接/文章讲解:programmercarl.com/0202.%E5%BF…

 1. 两数之和 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        // 定义一个哈希集合
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            // 寻找目标数
            int findNum = target - nums[i];
            // 在哈希表中查询
            if (map.containsKey(findNum)) {
                //如果查询到则将值赋值给result数组输出
                result[0] = i;
                result[1] = map.get(findNum);
                break;
            } 
            //如果查询不到,则将已经访问过的值和索引放入哈希表
            map.put(nums[i], i);
        }
        return result;

    }
}

题目链接/文章讲解/视频讲解:programmercarl.com/0001.%E4%B8…