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


解题思路:

用HashMap, 但要注意用法的优化,不用将nums[]里所有的数据存储到hashmap里才开始比较,一边存一边比较,若成功则直接返回,能减少时间。

So the simplest solution using a HashMap is to simply throw all the data in there to start with, then iterate through all of the numbers to see if (target-num) is in there, and if it is, return {lower index, higher index}.

However, we can cut down on some runtime and code length by doing it in a single for loop.

We know that the first number is strictly less than the second number (implying not equal), so if we are returning {value found in HashMap, current loop iteration} then we can be certain that we will never have to insert a value in the HashMap before we check if its difference is. Because of this fact, we can do the inserting and checking in the same loop with no issues. This saves a bit on runtime and memory because it means that you are not guaranteed to have to save all of the data in the HashTable at the start.


Java code:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0; i< nums.length; i++){
            int diff = target - nums[i];
            if(map.containsKey(diff)){
                int[] result = {map.get(diff), i+1};
                return result;
            }
            map.put(nums[i],i+1);
        }
        return null;
    }
}

Reference:

1. https://leetcode.com/discuss/19298/very-short-and-simple-java-code-for-two-sum

 

posted @ 2015-10-17 02:16  茜茜的技术空间  阅读(262)  评论(0编辑  收藏  举报