1. 两数之和 第454题.四数相加II (哈希表)

1. 两数之和

Accept

可用map.containsKey()

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Integer> list = Arrays.asList(2, 7, 11, 15);
        int target = 9;
        List<Integer> res = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            map.put(list.get(i),i);
        }
        for (int i = 0; i < list.size(); i++) {
            int temp = target - list.get(i);
            if (map.getOrDefault(temp, null) != null){
                res.add(i);
                res.add(map.get(temp));
                break;
            }
        }
        System.out.println(res);

    }

}

第454题.四数相加II

accept

时间复杂度高了 为 3次方

public class test {
    public static void main(String[] args) {
        int a[]= {1, 2};
        int b[]= {-2,-1};
        int c[]= {-1, 2};
        int d[]= { 0, 2};
        Set<Integer> hash = new HashSet<>();
        for(int t : d){
            hash.add(t);
        }
        int sum = 0;
        for (int j : b) {
            for (int k : a) {
                for (int value : c) {
                    if (hash.contains(-(j + k + value))) {
                        sum++;
                    }
                }
            }
        }
        System.out.println(sum);

    }

}

可改成 2次方复杂度–双for循环:

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        //统计两个数组中的元素之和,同时统计出现的次数,放入map
        for (int i : nums1) {
            for (int j : nums2) {
                int sum = i + j;
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
        //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
        for (int i : nums3) {
            for (int j : nums4) {
                res += map.getOrDefault(0 - i - j, 0);
            }
        }
        return res;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值