两数之和

给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它的数组下标。

你可以假设每种输入只会对应一个答案,但是,数组中同一个元素在答案里不能重复出现。

可以按任意顺序返回答案。

 

 

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> storeNums = new HashMap<>(nums.length, 1);
        for (int i = 0; i < nums.length; i++) {
            int another = target - nums[i];
            Integer anotherIndex = storeNums.get(another);
            if(null != anotherIndex) {
                result[0] = anotherIndex;
                result[1] = i;
            }
            else {
                storeNums.put(nums[i], i);
            }
        }
        return result;
    }


    public static void main(String[] args) {
        int[] nums = {2,5,7,13,8};
        int target = 10;
        System.out.println(Arrays.toString(twoSum(nums, target)));
    }
}

  返回答案:

[0, 4]

  

posted @ 2024-03-24 19:20  宝山方圆  阅读(3)  评论(0编辑  收藏  举报