Leetcode - 两数之和

问题描述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。


示例:

  • 给定 nums = [2, 7, 11, 15], target = 9
  • 因为 nums[0] + nums[1] = 2 + 7 = 9
  • 所以返回 [0, 1]

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
public void testTwoSum() {
int[] arrays = {3, 3};
arrays = twoSum(arrays, 6);
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
}

public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int component = target - nums[i];
if(map.containsKey(component)){
return new int[]{map.get(component),i};
} else {
map.put(nums[i],i);
}
}
throw new IllegalArgumentException("error");
}

Powered by Hexo

Copyright © 2016 - 2019 When I think of you, I smile. All Rights Reserved.

UV : | PV :