leetcode之Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

这道题是最开始刷leetcode的时候做的,现在按照顺序刚好又到它,于是拿过来又看了一下源码。这道题其实算是比较简单的,最主要的就是看hashmap怎么使用。

下面附上我的源码

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        Integer index1 = 0;
        Integer index2 = 0;
        Map<Integer, Integer> numberMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            Integer diff = target - numbers[i];
            if (null != numberMap.get(diff)) {
                index1 = i + 1;
                index2 = numberMap.get(diff) + 1;
                if (index1 != index2) {
                    if (index1.intValue() > index2.intValue()) {
                        Integer tmp = index1;
                        index1 = index2;
                        index2 = tmp;
                    }
                    break;
                }
            } else {
                numberMap.put(numbers[i], i);
            }
        }
    int[] result = {index1.intValue(), index2.intValue()};
    return result;
    }
}

  

原文地址:https://www.cnblogs.com/gracyandjohn/p/4401626.html