Leetcode1 两数求和
程序员文章站
2022-04-04 09:49:36
...
Leetcode1 两数求和
题目描述
解题代码
public class TwoSum
{
public static void main(String[] args)
{
int[] nums={11,15,2,7};
int target=9;
System.out.println(Arrays.toString(twoSum(nums, target)));
}
public static int[] twoSum(int[] nums,int target) {
if (nums==null||nums.length<2)
{
return new int[] {-1,-1};
}
int[] res=new int[] {-1,-1};
HashMap<Integer, Integer>map=new HashMap<>();
for (int i = 0; i < nums.length; i++)
{
//containsKey方法——判断是否包含指定的键名
if (map.containsKey(target-nums[i]))
{
res[0]=map.get(target-nums[i]);
res[1]=i;
break;
}
map.put(nums[i], i);
}
return res;
}
}
上一篇: leetcode 1 两数之和
下一篇: leetcode1:两数求和