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

题目链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路:(1)暴力法,遍历每个元素 x,并查找是否存在一个值与 target−x 相等的目标元素。

class Solution 
{
    public int[] twoSum(int[] nums, int target) 
    {
        for(int i=0; i<nums.length; i++)
        {
            for(int j=i+1; j<nums.length; j++)
            {
                if(target - nums[i] == nums[j])
                    return new int[]{i,j};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

(2)hashmap两次迭代

在第一次迭代中,我们将每个元素的值和它的索引添加到表中。

 把数值作为 key,把数值所在的下标作为 value

然后,在第二次迭代中,我们将检查每个元素所对应的目标元素(target - nums[i])  是否存在于表中。

注意,该目标元素不能是 nums[i]本身!

用到的函数的意义:

containsKey(Object key) 
返回值类型:boolean   如果此映射包含对于指定键的映射关系,则返回 true。

put(K key, V value) 
在此映射中关联指定值与指定键。

get(Object key) 
返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回 null。
class Solution 
{
    public int[] twoSum(int[] nums, int target) 
    {
        Map<Integer,Integer> hash = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++)
        {
            hash.put(nums[i], i);
        }
        for(int i=0; i<nums.length; i++)
        {
            if(hash.containsKey(target - nums[i]) && hash.get(target - nums[i]) != i)
                return new int[]{i, hash.get(target - nums[i])};
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

 (3)hashmap一次迭代

在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。

class Solution {
    public int[] twoSum(int[] nums, int target) 
{
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) 
        {
            int complement = target - nums[i];
            if (map.containsKey(complement)) 
            {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

 

  • 36
    点赞
  • 128
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值