[LeetCode] 1. Two Sum

Two Sum

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].
Given nums = [3,2,4], target = 6,
Because nums[1] + nums[2] = 2 + 4 = 6,
return [1, 2].
Given nums = [3, 3], target = 6,
Because nums[0] + nums[1] = 3 + 3 = 6,
return [0, 1].

解析

使用一个hash表存储在数组中出现的数的下标。

C++解法

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        int size = nums.size();
        map<int,int> num;
        if(size<2)
            return res;
        for(int i=0;i<size;i++){
            int index1 = num[target - nums[i]];
            if(index1 > 0 && index1-1 != i){  
                res.push_back(index1-1);
                res.push_back(i);
                return res;
            }
            num[nums[i]] = i+1;
        }
        return res;
    }
};

python解法

class Solution(object):
    def twoSum(self, nums, target):
        if(len(nums)<=1):
            return False;
        numdict = {}
        for i in range(len(nums)):
            if target-nums[i] in numdict:
                return [numdict[target-nums[i]], i]
            else:
                numdict[nums[i]] = i;
上一篇:cf----2019-09-14(You Are Given a Decimal String...,XOR Guessing,Boxers)


下一篇:菜鸟+Springboot+java.lang.IllegalArgumentException: The given id must not be null!