(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

 

使用map,遍历一遍

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         // if(nums.size() == 0 ) return NULL;
 5         unordered_map<int,int> umap;
 6         vector<int> ret(2,-1);
 7         for(int i = 0;i < nums.size();++i)
 8         {
 9             if(umap.find(target-nums[i]) == umap.end())
10                 umap[nums[i]] = i;
11             else
12             {
13                 ret[0] = umap[target-nums[i]]+1;
14                 ret[1] = i+1;
15             }
16         }
17         return ret;
18         
19     }
20 };

 JAVA 做法,使用hashmap,进行匹配

Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    	int[] a = new int[2];
    	for (int i = 0; i < nums.length; ++i)
    	{
    		Integer n =map.get(nums[i]);
    		if(n==null){
    			map.put(nums[i], i);
    		}
    		//进行匹配
    		n = map.get(target-nums[i]);
    		if(n!=null && n < i){
    			a[0] = n+1;
    			a[1] = i+1 ;
    			return a;
    		}
    	}
    	return a;

  

posted @ 2015-08-22 21:42  sunalive  Views(122)  Comments(0)    收藏  举报