【leetcode学习记录】

两数之和

此题有两种方法可以求解。

1.普通方法

最简单的方法就是两重for循环暴力求解。

//leetcode-1
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0; i < nums.length - 1; i++){
            for(int j = i + 1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}

2.进阶方法

使用HashMap可以降低其时间复杂度,Key存储值,Value存储下标,只进行一趟循环,每次判断target - nums[i]是否存在于map中,如果存在则直接返回两下标值,不存在就将当前点存入map中。

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

四数相加

题目中给出了四个数组,将其分为两组,两个为一组,前两组将数组元素之和存到HashMap中,Key为数组之和,Value为此和出现的次数。然后在后两组数组中循环,判断(0-后两数组元素之和)是否存在于map中,并将其对应出现次数加入到结果中。

//leetcode-454
class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map map = new HashMap();
        int count = 0;
        for(int i : nums1){
            for(int j : nums2){
                int key = i + j;
                int value = (int) map.getOrDefault(key,0) + 1;
                map.put(key, value);
            }
        }
        for(int i : nums3){
            for(int j : nums4){
                if(map.containsKey(0 - i - j)){
                    count += (int) map.get(0 - i - j);
                }
            }
        }
        return count;
    }
}

未完待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值