# Leetcode 1:两数之和（最详细解决方案！！！）

给定 nums = [2, 7, 11, 15], target = 9



class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
len_nums = len(nums)
for i in range(len_nums):
for j in range(i + 1, len_nums):
if nums[i] + nums[j] == target:
return [i, j]
return []


class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
len_nums = len(nums)
for i in range(len_nums):
dif = target - nums[i]
if dif in nums[i+1:]:
dif_index = nums[i + 1:].index(dif)+i+1
return [i, dif_index]
return []


class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_len = len(nums)
for i in range(nums_len):
dif = target - nums[i]
if dif in nums[:i]:
return [nums.index(dif), i]
return []


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


class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i)
{
if (m.count(target - nums[i]))
{
return {m[target - nums[i]], i};
}
m[nums[i]] = i;
}
return {};
}
};


©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客