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



### 解答

class Solution(object):

def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

dic = dict(zip(nums, range(len(nums))))
for i in range(len(nums)):
j = dic.get(target-nums[i], -1)
if j >-1 and i < j:
return [i,j]



dic = {}
for i, x in enumerate(nums):
dic[x] = i
# 有重复的也没有事儿

for i, x in enumerate(nums):
if (target-x) in dic and dic[target-x] > i:
return [i, dic[target-x]]

return None



class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i, x in enumerate(nums):

if target-x in dic:
return [dic[target-x], i]

if x not in dic:
dic[x] = i



class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//申请一个对象
unordered_map<int, int> m;
vector<int> res;
for(int i=0;i<nums.size();i++){
m[nums[i]] = i;
}
for(int i=0;i<nums.size();i++){
int t=target-nums[i];
if(m.count(t) && m[t] !=i){
res.push_back(i);
res.push_back(m[t]);
break;
}
}

return res;
}
};