leetCode刷题记录(1题)
题目:两数之和
题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
用Java语言进行编写
做题心得
1.首先自己先写了一版,具体思路是这样的:
1)定义两个指针,慢指针i,快指针j,其次,因为题目要求,只有一种情况满足条件,所以可以定义一个长度为2的数组res[2],用来接收满足题目要求的元素的下标。
2)利用两层for循环,外层用i,内层用j
3)定义i初始为0,j=i+1,开始遍历
4)if判断,如果有nums[j]+nums[i] == target,则将res[0] = i,res[1] = j,再return res
2. 参考一下官方答案,现将官方答案的解题思路记录下来:
利用hashmap,比如a+b=target,那么,遍历数组nums,先遍历到a,然后将target-a的值存入hashmap的键列中,并将其数组对应的下标存入值列,再接着遍历,当遍历到b时,利用get方法,判断get(target-a)对应的值是否存在,若存在,则res[0] = hm.get(nums[i]),res[1] = i,再return res
代码
代码一:
class Solution {
public int[] twoSum(int[] nums, int target) {
int temp[] = new int[2];
for(int i = 0;i<nums.length;i++)
{
for(int j = i+1;j<nums.length;j++)
{
if(nums[i]+nums[j]==target)
{
temp[0] = i;
temp[1] = j;
return temp;
}
}
}
return null;
}
}
代码二:
class Solution {
public int[] twoSum(int[] nums, int target) {
int res[] = new int[2];
Map<Integer,Integer> hm = new HashMap<>();
for(int i = 0;i<nums.length;i++)
{
if(hm.get(nums[i]) != null)
{
res[0] = hm.get(nums[i]);
res[1] = i;
return res;
}
hm.put(target - nums[i], i);
}
return null;
}
}