java two sum 讲解_【LeetCode 力扣】1. Two Sum 两数之和 Java 解法

LeetCode的第一题,英文单词书中 Abandon 一般的存在,让我们来看一下题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

从题目中我们可以得知此题必有答案可解,容易想到将数组中所有元素装进哈希表 map 中,又由于要返回的是数组下标,因此将数组元素作为哈希表的key,数组下标作为哈希表的value;

将数组元素装进 map 以后对数组所有元素再次使用for循环,用target目标值对每一个元素进行相减得到 t;如果此时 map 的key 中含有 t 并且 其value不等于当前的 i,就说明我们已经得到了所需的答案,此时只需返回 当前的 i 值和哈希表中对应 t 的 value即可。

代码实现:

classSolution {public int[] twoSum(int[] nums, inttarget) {

HashMap map = new HashMap();int[] ans = new int[2];//将数组元素装进哈希表 map 中

for (int i = 0; i <= nums.length; i++){

map.put(nums[i], i);

}for(int i = 0; i <= nums.length; i++){int t = target -nums[i];//如果 map 中含有答案则返回其下标

if (map.containsKey(t) && map.get(t) !=i){

ans[0] =i;

ans[1] =map.get(t);

}

}returnans;

}

}

由于两次循环的条件是一样的,用两个for就会略显累赘,因而在这里可以把代码改的简洁一点:

classSolution {public int[] twoSum(int[] nums, inttarget) {

HashMap map = new HashMap();int[] ans = new int[2];//合并两个for循环

for(int i = 0; i <= nums.length - 1; i++){int t = target -nums[i];if (map.containsKey(t) && map.get(t) !=i){

ans[0] =i;

ans[1] =map.get(t);

}

map.put(nums[i], i);

}returnans;

}

}

LeetCode刷题是一个漫长的过程,笔者也不过刚刚开始;为了更好的学习故而写下自己的心得与体会.正所谓路漫漫其修远兮,吾将上下而求索。

笔者水平有限,如果有什么错误还请不吝赐教!

参考资料:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值