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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

題目:

  在一個int陣列中,找到哪兩個數相加等於target,並傳回兩個數在陣列中的索引值,每次都只能有一個答案,並且不能使用兩個相同的數

解答:

  

class TwoSun1 {
     private static int[] res;

    public static void main(String[] args) {
        int nums[] = {2, 7, 11, 15};
        int target = 9;
        twoSum(nums, target);
        System.out.print("[" + res[0] + ", " + res[1] + "]");

    }
    public static int[] twoSum(int nums[], int target) {
        res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) { // 如果map中有target-nums[i]的元素
                res[0] = map.get(target - nums[i])
                res[1] = i; //i=1
            } else {
                map.put(nums[i], i); //使用HashMap存每個數的值和索引
            }

        }
        return res;
    }
}

文章標籤
全站熱搜
創作者介紹
創作者 金城式 的頭像
金城式

金城式的程式筆記

金城式 發表在 痞客邦 留言(0) 人氣(11)