LeetCode:一个数组中两个数的和

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

题目的要求是:从数组中找出两个数,使其和为特定值target。例如nums = [2, 7, 11, 15], target = 9,因为2+7=9,返回[0, 1]。

import java.util.HashMap;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: AddTwoNumber
 * @Description: 在一个数组中找出两个数刚好等于某个值
 * @date 2018/10/12 8:50
 **/

public class AddTwoNumber {
    public static void main(String[] args) {

        int arr[] = {1, 2, 3, 4, 5};
        int target = 5;
        HashMap<Integer, Integer> hashMap = addTwoNumbers(arr, target);
        for (int key : hashMap.keySet()) {
            System.out.println(key + ":" + hashMap.get(key));
        }
    }

    private static HashMap<Integer, Integer> addTwoNumbers(int[] arr, int target) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        HashMap<Integer, Integer> newHashMap = new HashMap<>();

        for (int i = 0; i < arr.length; i++) {
            hashMap.put(arr[i], i);
        }

        for (int index = 0; index < arr.length; index++) {
            int num = target - arr[index];
            if (hashMap.containsKey(num) && hashMap.get(num) != index && index < hashMap.get(num)) {
                newHashMap.put(index, hashMap.get(num));
            }
        }
        return newHashMap;
    }
}

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/83023107