天天看點

Leetcode116: 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

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res(2);
        int n = nums.size();
        map<int,int> mp;
        for(int i = 0; i < n; i++)
        {
            if(mp.find(target-nums[i]) == mp.end())
                mp[nums[i]] = i;
            else
            {
                res[0] = mp[target-nums[i]]+1;
                res[1] = i+1;
            }
        }
        return res;
    }
};
           

用unorderedmap比map快,一個是hash散列實作,一個是紅黑樹。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    	vector<int> res(2);
        unordered_map<int, int> mp;
        for (int i = 0; i < nums.size(); ++i)
        {
        	/* code */
        	if(mp.find(target-nums[i]) == mp.end())
        		mp[nums[i]] = i;
        	else{
        		res[0] = mp[target-nums[i]];
        		res[1] = i;
        		break;
        	}
        }
        return res;
    }
};
           

python代碼:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        mp={}
        for x in range(len(nums)):
        	if target-nums[x] in mp:
        		return [mp[target-nums[x]], x]
        	mp[nums[x]] = x