给定一个整数数组nums
和一个整数目标值target
,请你在该数组中找出和为目标值的那两个 整数,并返回它们的数组下标。
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
class Solution {
public int[] twoSum(int[] nums, int target) {
if (ArrayUtils.isEmpty(nums)) {
throw new IllegalArgumentException("数组为空");
}
Map<Integer, Integer> map = Maps.newHashMap();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("数组中没有符合条件的两个数");
}
}
原文:https://www.cnblogs.com/s-star/p/14534825.html