LeetCode —— 哈希表

持续更新中............... 

242. 有效的字母异位词

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

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

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

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

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

        for(int i = 0; i < 26; i++){
            if(record[i] != 0){
                return false;
            }
        }
        return true;
    }
}
class Solution {
    public boolean isAnagram(String s, String t) {
        char[] charS = s.toCharArray();
        Arrays.sort(charS);
        String strS = String.valueOf(charS);

        char[] charT = t.toCharArray();
        Arrays.sort(charT);
        String strT = String.valueOf(charT);
        
        return strS.equals(strT);
    }
}
class Solution {
    public boolean isAnagram(String s, String t) {
        int[] arrayS = new int[26];
        for(int i = 0; i < s.length(); i++){
            arrayS[s.charAt(i) - 'a']++;
        }

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

        return Arrays.equals(arrayS, arrayT);
    }
}

383. 赎金信

给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。如果可以,返回 true ;否则返回 false 。magazine 中的每个字符只能在 ransomNote 中使用一次。

示例1:输入:ransomNote = "a", magazine = "b"         输出:false

示例2:输入:ransomNote = "aa", magazine = "ab"         输出:false

示例3:输入:ransomNote = "aa", magazine = "aab"         输出:true

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] record = new int[26];

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

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

        for(int i = 0; i < 26; i++){
            if(record[i] < 0){
                return false;
            }
        }

        return true;
    }
}

49. 字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。

示例1:输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]        输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for(int i = 0; i < strs.length; i++){
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String str = String.valueOf(chars);
            if(map.containsKey(str)){
                map.get(str).add(strs[i]);
            }else{
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                map.put(str, list);
            }
        }
        return new ArrayList<>(map.values());
    }
}

438.找到字符串中所有字母异位词

给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。

示例1:输入: s = "cbaebabacd", p = "abc"         输出: [0,6]

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<>();

        int[] target = new int[26];
        for(int i = 0; i < p.length(); i++){
            target[p.charAt(i) - 'a']++;
        }

        int left = 0;
        int right = 0;
        int[] window = new int[26];
        while(right < s.length()){
            window[s.charAt(right) - 'a']++;
            if(right - left + 1 == p.length()){
                if(Arrays.equals(target, window)){
                    list.add(left);
                }
                window[s.charAt(left) - 'a']--;
                left++;
            }

            right++;
        }

        return list;
    }
}

349. 两个数组的交集

给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。

示例1:输入:nums1 = [1,2,2,1], nums2 = [2,2]         输出:[2]

示例2:输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]         输出:[9,4]

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        for(int i : nums1){
            set.add(i);
        }

        Set<Integer> resultSet = new HashSet<>();
        for(int i : nums2){
            if(set.contains(i)){
                resultSet.add(i);
            }
        }
        
        return resultSet.stream().mapToInt(x -> x).toArray();
    }
}

350. 两个数组的交集II

给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。

示例1:输入:nums1 = [1,2,2,1], nums2 = [2,2]         输出:[2,2]

示例2:输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]         输出:[4,9]

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        for(int i : nums1){
            list.add(i);
        }
        
        List<Integer> resultList = new ArrayList<>();
        for(int i : nums2){
            if(list.contains(i)){
                resultList.add(i);
                list.remove(list.indexOf(i));
            }
        }
        return resultList.stream().mapToInt(x -> x).toArray();
    }
}
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int[] record = new int[1001];    //题目中给出:最大为1000
        for(int i : nums1){
            record[i]++;
        }

        List<Integer> list = new ArrayList<>();
        for(int i : nums2){
            if(record[i] > 0){
                list.add(i);
                record[i]--;
            }
        }

        return list.stream().mapToInt(x -> x).toArray();
    }
}

202. 快乐数

编写一个算法来判断一个数 n 是不是快乐数。「快乐数」 定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果这个过程 结果为 1,那么这个数就是快乐数。如果 n 是 快乐数 就返回 true ;不是,则返回 false 。

示例1:输入:n = 19         输出:true

解释:1^2+9^2=82        8^2+2^2=68        6^2+8^2=100        1^2+0^2+0^0=1

class Solution {
    public boolean isHappy(int n) {
        List<Integer> list = new ArrayList<>();
        while(n != 1 && !list.contains(n)){
            list.add(n);
            n = getNextNumber(n);
        }
        return n==1;
    }

    public int getNextNumber(int n){
        int sum = 0;
        while(n > 0){
            int temp = n % 10;
            sum += temp * temp;
            n = n / 10;
        }
        return sum;
    }
}

1. 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

示例1:输入:nums = [2,7,11,15], target = 9         输出:[0,1]

示例2:输入:nums = [3,2,4], target = 6         输出:[1,2]

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 temp = target - nums[i];
            if(map.containsKey(temp)){
                result[0] = map.get(temp);
                result[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

454. 四数相加II

给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:0 <= i, j, k, l < n;nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

示例 1:输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]        输出:2
解释:① (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0; ② (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int result = 0;

        Map<Integer, Integer> map = new HashMap<>();
        for(int i : nums1){
            for(int j : nums2){
                int temp = i + j;
                if(map.containsKey(temp)){
                    map.put(temp, map.get(temp) + 1);
                }else{
                    map.put(temp, 1);
                }
            }
        }

        for(int i : nums3){
            for(int j : nums4){
                int temp = 0 - (i + j);
                if(map.containsKey(temp)){
                    result += map.get(temp);
                }
            }
        }

        return result;
    }
}

15. 三数之和

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。

示例1:输入:nums = [-1,0,1,2,-1,-4]        输出:[[-1,-1,2],[-1,0,1]]
解释:①nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 ;②nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 ;③nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);

        // 找出 a + b + c = 0
        // a = nums[i], b = nums[left], c = nums[right]
        for(int i = 0; i < nums.length; i++){
            if(nums[i] > 0){
                return list;
            }

            // 对a去重
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }

            int left = i + 1;
            int right = nums.length - 1;
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if(sum > 0){
                    right--;
                }else if(sum < 0){
                    left++;
                }else if(sum == 0){
                    list.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // 对c去重
                    while(left < right && nums[right] == nums[right - 1]){
                        right--;
                    }
                    // 对b去重
                    while(left < right && nums[left] == nums[left + 1]){
                        left++;
                    }
                    right--;
                    left++;
                }
            }
        }

        return list;
    }
}

18. 四数之和

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):0 <= a, b, c, d < n;a、b、c 和 d 互不相同;nums[a] + nums[b] + nums[c] + nums[d] == target;你可以按 任意顺序 返回答案 。

示例1:输入:nums = [1,0,-1,0,-2,2], target = 0         输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

示例2:输入:nums = [2,2,2,2,2], target = 8         输出:[[2,2,2,2]]

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);

        for(int i = 0; i < nums.length; i++){
            if(nums[i] > 0 && nums[i] > target){
                return list;
            }

            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }

            for(int j = i + 1; j < nums.length; j++){
                if(j > i + 1 && nums[j] == nums[j-1]){
                    continue;
                }

                int left = j + 1;
                int right = nums.length - 1;
                while(left < right){
                    long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
                    if(sum > target){
                        right--;
                    }else if(sum < target){
                        left++;
                    }else if(sum == target){
                        list.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while(left < right && nums[right - 1] == nums[right]){
                            right--;
                        }
                        while(left < right && nums[left + 1] == nums[left]){
                            left++;
                        }
                        right--;
                        left++;
                    }
                }
            }
        }
        return list;
    }
}

1365. 有多少小于当前数字的数字

给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。

示例1:输入:nums = [8,1,2,2,3]         输出:[4,0,1,1,3]

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();

        int[] result = Arrays.copyOf(nums, nums.length);
        Arrays.sort(result);

        for(int i = 0; i < result.length; i++){
            if(!map.containsKey(result[i])){
                map.put(result[i], i);       //排序之后,下标就是比自身小的数的个数
            }
        }

        for(int i = 0; i < nums.length; i++){
            result[i] = map.get(nums[i]);
        }
        return result;
    }
}

1207. 独一无二的出现次数

给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false

示例1:输入:arr = [1,2,2,1,1,3]         输出:true

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < arr.length; i++){
            map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
        }

        Set<Integer> set = new HashSet<>();
        for(Integer value : map.values()){
            if(set.contains(value)){
                return false;
            }else{
                set.add(value);
            }
        }
        return true;
    }
}

205. 同构字符串

给定两个字符串 s 和 t ,判断它们是否是同构的。如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。

示例1:输入:s = "egg", t = "add"   输出:true

示例2:输入:s = "foo", t = "bar"         输出:false

示例3:输入:s = "paper", t = "title"  输出:true

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> map1 = new HashMap<>();
        Map<Character, Character> map2 = new HashMap<>();
        for(int i = 0; i < s.length(); i++){
            if(!map1.containsKey(s.charAt(i))){
                map1.put(s.charAt(i), t.charAt(i));
            }
            if(!map2.containsKey(t.charAt(i))){
                map2.put(t.charAt(i), s.charAt(i));
            }

            if(map1.get(s.charAt(i)) != t.charAt(i) || map2.get(t.charAt(i)) != s.charAt(i)){
                return false;
            }
        }
        return true;
    }
}

1002. 查找共用字符

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。

示例1:输入:words = ["bella","label","roller"]         输出:["e","l","l"]

示例2:输入:words = ["cool","lock","cook"]         输出:["c","o"]

class Solution {
    public List<String> commonChars(String[] words) {
        List<String> result = new ArrayList<>();
        int[] frequency = new int[26];  // 用来统计所有字符串里字符出现的最小频率
        for(int i = 0; i < words[0].length(); i++){
            frequency[words[0].charAt(i) - 'a']++;
        }

        // 统计除第一个字符串外字符的出现频率
        for(int i = 1; i < words.length; i++){
            int[] other = new int[26];
            for(int j = 0; j < words[i].length(); j++){
                other[words[i].charAt(j) - 'a']++;
            }

            // 更新frequency,保证frequency里统计26个字符在所有字符串里出现的最小次数
            for(int k = 0; k < 26; k++){
                frequency[k] = Math.min(frequency[k], other[k]);
            }
        }

        for(int i = 0; i < 26; i++){
            while(frequency[i] != 0){
                char c = (char) (i + 'a');
                result.add(String.valueOf(c));
                frequency[i]--;
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值