题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
给定一个整数数组,返回这两个数字的索引,使它们合计成一个特定的目标。
示例:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
首先,第一种办法,也是最容易想到的办法,就是使用两个for循环遍历数组,找到符合要求的两个元素并返回,代码如下:
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 (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
实际上,这里使用c++中的map结构更容易实现目标,代码如下:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
这里用到了map中的containsKey方法,方法具体描述可以到我的这篇博客查看containsKey方法