1. 两数之和

这篇博客探讨了两种解决两数之和问题的方法:暴力解法和哈希表法。暴力解法通过双重循环遍历数组,但效率较低;哈希表法通过预处理数组,将元素及其索引入表,然后查找目标值的差值,显著提高了查找速度。文章对比了两种方法的时间和空间复杂度,并强调了优化的重要性。
摘要由CSDN通过智能技术生成
1. 两数之和
  • 暴力解法:通过两个for循环逐步遍历,判断是否有符合条件的答案
  • 1.初始有对数据进行判断,比如数字比目标值大就不用判断,直接跳过,其实是不行的,因为里面有负数,最后相减也可以得出正确答案,这是最初版本。
class Solution {
    public int[] twoSum(int[] nums, int target) {

        int[] dp = new int[2];
        for(int i = 0 ;i <nums.length;i++){
            if(nums[i]>Math.abs(target)){
                continue;
            }else{
                for(int j = i+1;j<nums.length;j++){
                    if(target == nums[i]+nums[j]){
                        dp[0] = i;
                        dp[1] = j;
                    }
                }
            }
        }
        return dp;

    }
}
  • 2.之后发现有负数这种情况后,直接取消了判断,但这样会增加时间复杂度,没有做好优化。
  class Solution {
    public int[] twoSum(int[] nums, int target) {

        int[] dp = new int[2];
        for(int i = 0 ;i <nums.length;i++){   
            for(int j = i+1;j<nums.length;j++){
                if(target == nums[i]+nums[j]){
                    dp[0] = i;
                    dp[1] = j;
                }
            }
            
        }
        return dp;

    }
  }

Snipaste_2022-05-31_09-41-33

Snipaste_2022-05-31_09-51-49

  • 哈希表法:先将数据存入哈希表中,再使用目标值依次减去数组中的数据,再从哈希表中找是否有符合条件的值,如果有,将下标传给result数组,返回结果。
class Solution {
    // HashMap
    // N is the size of nums
    // Time Complexity: O(N)
    // Space COmplexity: O(N)
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        //定义hashMap
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i=0;i < nums.length;i++){
            //将所有数据存入hash表中
            map.put(nums[i],i);
        }
        //使用目标值减去数组中的值,查看表中是否有符合条件的值就返回
        for(int j=0;j < nums.length; j++){
            int diff = target - nums[j];
            if(map.containsKey(diff)&&map.get(diff)!=j){
                result[0] = j;
                result[1] = map.get(diff);
                return result;

            }
        }
        return result;
    }
}

Snipaste_2022-05-31_10-32-42

Snipaste_2022-05-31_10-33-08

Snipaste_2022-05-31_10-36-17

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抗争的小青年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值