[leetcode] Two Sum

思路:只需遍历一次数组,利用HashMap保存数组元素和下标,如果target-数组元素存在HashMap的key中,则返回结果,如果不存在,则put到HashMap中,注意,这种遍历保证了数组的下标肯定不小于HashMap中的下标。

Java代码:

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> num_index = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (num_index.containsKey(target - nums[i])) {
                return new int[] {num_index.get(target - nums[i]) + 1, i + 1};
            }
            num_index.put(nums[i], i);
        }
        throw new IllegalArgumentException("No solution.");
    }
原文地址:https://www.cnblogs.com/lasclocker/p/4713120.html