您的位置:首页 > 编程语言 > C语言/C++

【leetcode】1. Two Sum(Python & C++)

2017-07-24 17:08 441 查看

1. Two Sum

题目链接

1.1 题目描述:

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

1.2 解题思路:

思路一:第一个思路就是两次遍历,找到第一个元素,二次遍历其后面的元素,如果发现这两个元素的和为target,则两元素坐标push进vector。

思路二:利用map,一次遍历。在遍历时,获取target-当前遍历的元素的值,然后在map中查找是否有这个值,如果有,则将其map对应的值作为坐标值,连通遍历元素的坐标值一起push进vector;否则,则将当前遍历的这个元素的值与坐标放入map中。

1.3 C++代码:

1、思路一代码(233ms):

class Solution90 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>a;
for (int i = 0; i < nums.size();i++)
{
for (int j = i + 1; j < nums.size();j++)
{
if (target == (nums[i] + nums[j]))
{
a.push_back(i);
a.push_back(j);
return a;
}
}
}
return a;
}
};


2、思路二代码(13ms):

class Solution90_1 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int>m;
vector<int>a;
for (int i = 0; i, nums.size();i++)
{
int tofind = target - nums[i];
if (m.find(tofind)!=m.end())
{
a.push_back(m[tofind]);
a.push_back(i);
return a;
}
m[nums[i]] = i;
}
return a;
}
};


1.4 Python代码:

1、思路一代码(5865ms):

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


2、思路二代码(39ms):

class Solution1(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d={}
for i in range(0,len(nums)):
tofind=target-nums[i]
if tofind in d:
return [d[tofind],i]
d[nums[i]]=i
return a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: