Difficulty: Easy

Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.

You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.

You can return the answers in any order.

Their thinking

With the convenience of hash table, the difference and subscript between the item traversed and the target value are saved each time, so that when the next convenience reaches the difference value, the information of both can be obtained

Answer key

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[] {}; }Copy the code

test

TwoSum twoSum = new TwoSum();

@Test
public void test_case1(a) {
    int[] actual = twoSum.twoSum(new int[] {2.7.11.15}, 9);
    Assertions.assertArrayEquals(new int[] {0.1}, actual);
}

@Test
public void test_case2(a) {
    int[] actual = twoSum.twoSum(new int[] {3.2.4}, 6);
    Assertions.assertArrayEquals(new int[] {1.2}, actual);
}

@Test
public void test_case3(a) {
    int[] actual = twoSum.twoSum(new int[] {3.3}, 6);
    Assertions.assertArrayEquals(new int[] {0.1}, actual);
}
Copy the code