难度:简单
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
解题思路
利用哈希表的便利性,将每次遍历到的项与目标值的差值和下标进行保存,这样当下次便利到差值的时候,将能获取到两者的信息
题解
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
Map<Integer, Integer> map = new HashMap<>(length);
for (int index = 0; index < length; index++) {
if (map.containsKey(target - nums[index])) {
return new int[]{map.get(target - nums[index]), index};
}
map.put(nums[index], index);
}
return new int[]{};
}
测试
TwoSum twoSum = new TwoSum();
@Test
public void test_case1() {
int[] actual = twoSum.twoSum(new int[]{2, 7, 11, 15}, 9);
Assertions.assertArrayEquals(new int[]{0, 1}, actual);
}
@Test
public void test_case2() {
int[] actual = twoSum.twoSum(new int[]{3, 2, 4}, 6);
Assertions.assertArrayEquals(new int[]{1, 2}, actual);
}
@Test
public void test_case3() {
int[] actual = twoSum.twoSum(new int[]{3, 3}, 6);
Assertions.assertArrayEquals(new int[]{0, 1}, actual);
}