• 一、题目
  • 二、解题思路
  • 三、解题代码

    一、题目

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。

    二、解题思路

    用hashmap,hashmap是内部存储方式为哈希表的map结构。遍历数组,其中key存放目标值减去当前值,value存放对应索引。如果在遍历过程中发现map中存在与当前值相等的key,则返回结果。

    三、解题代码

    1. public class Solution {
    2. /*
    3. * @param numbers : An array of Integer
    4. * @param target : target = numbers[index1] + numbers[index2]
    5. * @return : [index1 + 1, index2 + 1] (index1 < index2)
    6. numbers=[2, 7, 11, 15], target=9
    7. return [1, 2]
    8. */
    9. public int[] twoSum(int[] numbers, int target) {
    10. HashMap<Integer,Integer> map = new HashMap<>();
    11. for (int i = 0; i < numbers.length; i++) {
    12. if (map.get(numbers[i]) != null) {
    13. int[] result = {map.get(numbers[i]) + 1, i + 1};
    14. return result;
    15. }
    16. map.put(target - numbers[i], i);
    17. }
    18. int[] result = {};
    19. return result;
    20. }
    21. }