1. Two Sum

来源:互联网 发布:哈工大 ltp 源码 编辑:程序博客网 时间:2024/06/05 00:57

Discription:

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


Explanation:

for each number in array, we can store its index into a map.
iterate number nums[i], we look up whether target-nums[i] is in the map.
if yes then the answer is [map[target-nums[i]], i]
else we set map[nums[i]]=i.


Implement code:
C++:
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> m;
        
        vector<int> ans(2, -1);
        
        for(int i=0;i!=nums.size(); ++i)
        {
            int k=target-nums[i];
            
            if(m.count(k))
            {
                ans[0]=m[k];
                ans[1]=i;
                break;
            }
            
            m[nums[i]]=i;
        }
        
        return ans;
    }
};

--------------------------------------


Java:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        
        Map m = new HashMap();
        
        for(int i=0;i<nums.length; ++i)
        {
            int k=target - nums[i];
            if(m.containsKey(k))
            {
                ans[0] = (int)m.get(k);
                ans[1] = i;
                return ans;
            }
            
            m.put(nums[i], i);
        }
        
        return ans;
    }
}

原创粉丝点击