【力扣刷题学习笔记04(哈希表)】

349. 两个数组的交集

力扣题目链接(opens new window)

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

349. 两个数组的交集

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

使用HashSet的方法

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);
            }
        }
        // 方法一stream()流将结果集合转化为数组
        return resSet.stream().mapToInt(x -> x).toArray();

        // 方法二使用另一个数组存放resSet
        int[] arr = new int[resSet.size()];
        int j = 0;
        for(int i : resSet){
            arr[j++] = i;
        }
        return arr;
    }
}

第202题. 快乐数

力扣题目链接(opens new window)

编写一个算法来判断一个数 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

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while(n > 0){
            int sum = getSum(n);
            if(sum == 1){
                return true;
            }
            if(record.contains(sum)){
                return false;
            }else{
                record.add(sum);
            }
            n = sum;
        }
        return n == 1;
    }
    private int getSum(int n){
        int sum = 0;
        while(n > 0){
            sum += (n % 10) * (n % 10);
            n/=10;
        }
        return sum;
    }
}

1. 两数之和

力扣题目链接(opens new window)

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

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

示例:

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

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

所以返回 [0, 1]

使用双指针方法解题

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //双指针解题
        int[] result = new int[2];
        int[] temp = new int[nums.length];
        int m = 0, n = 0;
        System.arraycopy(nums, 0, temp, 0, nums.length);
        Arrays.sort(nums);
        for(int i = 0, j = nums.length - 1;i<j;){
            int sum;
            sum = nums[i] + nums[j];
            if(sum<target){
                i++;
            }
            else if(sum>target){
                j--;
            }
            else if(sum == target){
                m = i;
                n = j;
                //已找到索引则跳出循环
                break;
            }
        }
        for(int a = 0;a<nums.length;a++){
            if(temp[a] == nums[m]){
                result[0] = a;
                //返回找到的第一个值的索引
                //避免有相同数值时返回同一个索引
                break;
            }
        }
        for(int a = 0;a<nums.length;a++){
            if(temp[a] == nums[n]){
                result[1] = a;
            }
        }
        return result;
    }
}

 使用哈希表(HashMap)解题

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

第454题.四数相加II

力扣题目链接(opens new window)

给定四个包含整数的数组列表 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 。所有整数的范围在 -2^28 到 2^28 - 1 之间,最终结果不会超过 2^31 - 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

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i : nums1){
            for(int j : nums2){
                int sum = i + j;
                //map.getOrDefault(sum, 0) 函数用于从 map 中获取指定键 sum 对应的值
                //如果键不存在,则返回默认值 0
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
        for(int i : nums3){
            for(int j : nums4){
                int sum = i + j;
                count += map.getOrDefault(0-sum, 0);
            }
        }
        return count;
    }
}
  • 时间复杂度: O(n^2)
  • 空间复杂度: O(n^2),最坏情况下A和B的值各不相同,相加产生的数字个数为 n^2

383. 赎金信

力扣题目链接(opens new window)

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

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

注意:

你可以假设两个字符串均只含有小写字母。

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

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i : nums1){
            for(int j : nums2){
                int sum = i + j;
                //map.getOrDefault(sum, 0) 函数用于从 map 中获取指定键 sum 对应的值
                //如果键不存在,则返回默认值 0
                map.put(sum, map.getOrDefault(sum, 0) + 1);
                //if(map.containsKey(sum)){
                //    int a = map.get(sum);
                //    map.put(sum, ++a);
                //}else{
                //    map.put(sum, 1);
                //}
            }
        }
        for(int i : nums3){
            for(int j : nums4){
                int sum = i + j;
                //if (map.containsKey(0-sum)){
                //    count += map.get(0-sum);
                //}
                count += map.getOrDefault(0-sum, 0);
            }
        }
        return count;
    }
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
  • 383. 赎金信

    力扣题目链接(opens new window)

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

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

    注意:

    你可以假设两个字符串均只含有小写字母。

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

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        //数组在哈希法中的应用
        //用以记录26个字符出现的次数
        int[] record = new int[26];
        //字符串是 Java 中的一个类,length() 是字符串类的一个方法
        //a 如果是一个数组,使用 a.length 可以获得数组的长度,这是因为数组是一个对象,具有 length 属性
        if(ransomNote.length() > magazine.length()){
            return false;
        }
        for(char i : magazine.toCharArray()){
            record[i-'a'] ++;
        }
        for(char j : ransomNote.toCharArray()){
            record[j-'a'] --;
        }
        for(int a : record){
            if(a < 0){
                return false;
            }
        }
        return true;
    }
}

第15题. 三数之和

力扣题目链接(opens new window)

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

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

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        //双指针法解题
        //三数之和,要注意三个数都需要做去重处理
        //List<List<Integer>>:这表示这是一个列表,其中每个元素都是一个整数列表
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);//从小到大排序
        for(int i = 0; i<nums.length; i++){
            //如果第一个数为正数则退出
            if(nums[i] > 0){
                return result;
            }
            //第一个数做去重
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            int slow = i + 1, fast = nums.length - 1;
            int sum = 0;
            while(slow < fast){
                sum = nums[i] + nums[slow] + nums[fast];
                if(sum > 0){
                    --fast;
                }else if(sum < 0){
                    ++slow;
                }else{
                    result.add(Arrays.asList(nums[i], nums[slow], nums[fast]));
                    //对第二第三个数做去重
                    while(slow < fast && nums[slow] == nums[slow + 1]){slow++;}
                    while(fast > slow && nums[fast] == nums[fast - 1]){fast--;}
                    //slow和fast同时位移一步
                    slow++;
                    fast--;
                }
            }
        }
        return result;
    }
}

第18题. 四数之和

力扣题目链接(opens new window)

题意:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 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>> result = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0;i<nums.length;i++){
            if(nums[i] > 0 && nums[i] > target){
                return result;
            }
            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, 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{
                        result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while(left < right && nums[left+1] == nums[left]){left++;}
                        while(left < right && nums[right-1] == nums[right]){right--;}
                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }
}

  • 17
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值