leetcodeのHashTable

哈希表

这回,我决定一改题号顺序,而是根据特意的安排来安排题目顺序😋😋😋

242. 有效的字母异位词

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

示例 1:

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

示例 2:

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

说明:

  • 你可以假设字符串只包含小写字母。

放在了哈希表的专题里自然是要用到相关思想的,这是一道哈希思想简单使用的题目。关于哈希表就不多说了。那么实现哈希表的数据结构有很多种,这题使用数组 ,这是为什么呢?

该题只有26个英文字母,我们只需要创建一个26大小的char数组即可,字母编号是唯一,甚至避开了哈希碰撞的问题,此题不用数组更待何时用?

创建一个26大小的char数组hashTable遍历字符串t计数, t中哪个字母出现一次就在对应位置上加⒈, s中哪个字母出现一次就在对应位置上减⒈。

最后检查hashTable ,如果全部为0说明是字母异位词 ,反之则不是。

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length())return false;
        int[] hashTable = new int[26];
        for(int i = 0;i < t.length();i++){
            hashTable[s.charAt(i) - 'a']++;
            hashTable[t.charAt(i) - 'a']--;
        }
        for(int i = 0;i < hashTable.length;i++){
            if(hashTable[i] != 0)return false;
        }
        return true;
    }
}

349. 两个数组的交集

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

示例 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> set1 = new HashSet<Integer>();
        Set<Integer> set2 = new HashSet<Integer>();
        for (int num : nums1) {
            set1.add(num);
        }
        for (int num : nums2) {
            set2.add(num);
        }
        return getIntersection(set1, set2);
    }

    public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
        if (set1.size() > set2.size()) {
            return getIntersection(set2, set1);
        }
        Set<Integer> intersectionSet = new HashSet<Integer>();
        for (int num : set1) {
            if (set2.contains(num)) {
                intersectionSet.add(num);
            }
        }
        int[] intersection = new int[intersectionSet.size()];
        int index = 0;
        for (int num : intersectionSet) {
            intersection[index++] = num;
        }
        return intersection;
    }
}

202. 快乐数

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

「快乐数」定义为:

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

如果 n 是快乐数就返回 true ;不是,则返回 false

示例 1:

输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

示例 2:

输入:n = 2
输出:false

提示:

  • 1 <= n <= 231 - 1
  • 题目中说了会 「无限循环」,那么也就是说 「求和的过程中,sum会重复出现,这对解题很重要!」「当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法了。」

第一次遇到这样的题,应该不会马上想到 「如果该不是快乐数,则会进入一个死循环」

当知道了这一点后,其实该题就是名副其实的简单题了。

class Solution {

    public int getSum(int n){
        int sum = 0;
        while(n != 0){
            int m = n % 10;
            sum += m * m;
            n /= 10;
        }
        return sum;
    }

    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while(n != 1){
            if(set.contains(n))return false;
            set.add(n);
            n = getSum(n);
        }
        return true;
    }
}

1. 两数之和

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

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

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

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

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

根据上一题的思想, 「当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法了。」

那么问题来了,我们如何要快速判断什么呢?🧐🧐🧐

我们需要快速判断的是差值 ,因为相加等于target的2个数肯定来自nums ,那么 t a g e t − a = b taget - a = b tageta=b 其中 a a a b b b都属于nums ,那么我们只需要拿着 a a a判断 b b b是否在哈希表里即可。

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

454. 四数相加 II

难度中等330收藏分享切换为英文接收动态反馈

给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0

为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。

示例 1:

输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

输出:
2

解释 :

两个元组如下:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

因为这题是分别不同的4个数组中求和等于0 ,且最后要求的结果是有多少个不同的元组 。因此可用哈希

4个数怎么使用哈希呢?根据上一题两数之和的思想,我们可以将4个数组拆分成2组,每组2个数组。将看作

class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        int sumAB = 0;
        Map<Integer,Integer> map = new HashMap<>();
        for(int a : A){
            for(int b : B){
                sumAB = a + b;
                if(!map.containsKey(sumAB)){
                    map.put(sumAB, 1);
                }else{
                    map.put(sumAB, map.get(sumAB) + 1);
                }
            }
        }
        int sumCD = 0;
        int res = 0;
        for(int c : C){
            for(int d : D){
                sumCD = 0 - (c + d);
                if(map.containsKey(sumCD))res += map.get(sumCD);
            }
        }
        return res;
    }
}

383. 赎金信

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

示例 1:

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

这题一看就和242题很相似吧,只是最后的要求有些许的改变罢了。

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] alphabet = new int[26];
        for(int i = 0;i < magazine.length();i++){
            alphabet[magazine.charAt(i) - 'a']++;
        }
        for(int i = 0;i < ransomNote.length();i++){
            alphabet[ransomNote.charAt(i) - 'a']--;
            if(alphabet[ransomNote.charAt(i) - 'a'] < 0)return false;
        }
        return true;
    }
}

15. 三数之和

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 *a,b,c ,*使得 a + b + c = 0 请你找出所有和为 0 且不重复的三元组。

注意: 答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]

示例 2:

输入:nums = []
输出:[]

示例 3:

输入:nums = [0]
输出:[]

这题看上去貌似跟454. 四数相加 II很像,但其实完全变了, 哈希也并不很好的适用。

更好的是双指针思想。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        if(nums.length < 3 || nums == null)return lists;
        Arrays.sort(nums);
        for(int i = 0;i < nums.length;i++){
            if(nums[i] > 0)continue;
            if(i > 0 && nums[i] == nums[i - 1])continue;
            int left = i + 1;
            int right = nums.length - 1;
            while(left < right){
                if(nums[i] + nums[left] + nums[right] == 0){
                    lists.add(new ArrayList<>(Arrays.asList(nums[i], nums[left], nums[right])));
                    while(left < right && nums[++left] == nums[left - 1]);
                    while(right > left && nums[--right] == nums[right + 1]);
                }
                else if(nums[i] + nums[left] + nums[right] < 0){
                    while(left < right && nums[++left] == nums[left - 1]);
                }
                else{
                    while(right > left && nums[--right] == nums[right + 1]);
                }                
            }
        }
        return lists;
    }
}

18. 四数之和

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 abcd ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

根据上一题的思想,直接上代码吧

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        if (nums == null || nums.length < 4) {
            return lists;
        }
        Arrays.sort(nums);
        int length = nums.length;
        for (int i = 0; i < length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }
            if (nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
                continue;
            }
            for (int j = i + 1; j < length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                    break;
                }
                if (nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
                    continue;
                }
                int left = j + 1, right = length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        lists.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[++left] == nums[left - 1]);
                        while (left < right && nums[--right] == nums[right + 1]);
                    } 
                    else if (sum < target) {
                        while (left < right && nums[++left] == nums[left - 1]);
                    } 
                    else {
                        while (left < right && nums[--right] == nums[right + 1]);
                    }
                }
            }
        }
        return lists;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值