两数之和介绍

题目地址: https://leetcode-cn.com/problems/two-sum/
题目说明: 
   给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标.
你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使用两遍.

题目事例:
   给定nums = [2, 7, 11, 15], target = 9
   因为nums[0] + nums[1] = 2 + 7 = 9
   所以返回 [0, 1]

题目分析:
   你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使用两遍
   这两个说明其实是核心所在.
方法一:两遍hash方法,使用hash将时间复杂度降低为O(n)

public int[] twoSum(int[] nums, int target) {
   // 1.校验参数的有效性
   if (nums == null || nums.length == 0) { return new int[0]; }
   // 2.将数据保存保存到hash表中
   Map<Integer, Integer> hash = new HashMap<>();
   for (int i=0; i<nums.length; i++) {
     hash.put(nums[i], i);
   }
   // 3.遍历数据进行查询
   for (int i=0; i<nums.length; i++) {
     int val = target - nums[i];
     if (hash.containsKey(val) && hash.get(val) != i) {
       return new int[]{i, hash.get(val)};
     }
   }
   return new int[0];
 }
方法二:一遍hash方法,使用hash将时间复杂度降低为O(n)

// 1.采用1遍hash方式处理
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> valAndIdex = new HashMap<>();
    // 2.遍历当前数据获取目标数据
    for (int index = 0; index < nums.length; index++) {
        int temp = target - nums[index];
        Integer valIndex = valAndIdex.get(temp);
        if (valIndex != null && valIndex != index) {
            return new int[]{valIndex, index};
        }
        valAndIdex.put(nums[index], index);
    }
    throw new IllegalArgumentException("No two sum solution");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

荣华富贵8

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

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

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

打赏作者

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

抵扣说明:

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

余额充值