01.leetcode_twoSum

问题
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].

The return format had been changed to zero-based indices. Please read the above updated description carefully.


代码

import java.util.HashMap;

public class twoSum {
    public int[] twoSum(int[] numbers, int target) {
        HashMap map = new HashMap<>();
        int[] res = new int[2];

        for (int i = 0; i < numbers.length; i++) {

            if (map.containsKey(target - numbers[i])) {
                res[1] = map.get(target-numbers[i]);
                res[0] = i;
                break;
            }
            map.put(numbers[i], i);
        }


        return res;

    }

    public static void main(String[] args) {
        int [] num = {1,2,3,4,5};
        twoSum twoSum = new twoSum();
        int[] ints = twoSum.twoSum(num, 6);
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);

        }
    }
}

你可能感兴趣的:(leecode_Java)