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

通过一个哈希表快速查询每个数对应的组成目标值的数是否存在

构建hash表需要O(n)的时间复杂度

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> ret;
        map<int,int> m;
        for(int i=0;i<numbers.size();i++){
            m[numbers[i]]=i;
        }
        for(int i=0;i<numbers.size();i++){
            if(m.find(target-numbers[i])!=m.end()){
                int ind=m[target-numbers[i]];
                if(ind!=i){
                    ret.push_back(i+1);
                    ret.push_back(m[target-numbers[i]]+1);
                    break;
                }
            }
        }
        return ret;
    }
};
C++
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        HashMap<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
        for(int i=0;i<numbers.length;i++){
            hashMap.put(numbers[i], i);
        }
        int ret[]=new int[2];
        for(int i=0;i<numbers.length;i++){
            if(hashMap.containsKey(target-numbers[i])){
                if(hashMap.get(target-numbers[i])!=i){
                    ret[0]=i+1;
                    ret[1]=hashMap.get(target-numbers[i])+1;
                }
            }
        }
        Arrays.sort(ret);
        return ret;
    }
}
Java
posted @ 2013-09-15 11:21  懒猫欣  阅读(363)  评论(0编辑  收藏  举报