(LeetCode) 1. Two Sum

文章目录

  1. 1. Original URL: 1.Two Sum
  2. 2. My solutions:
    1. 2.1. With C++:
    2. 2.2. With Python:

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Difficulty: Easy
Tags: Array, Hash Table

Original URL: 1.Two Sum

My solutions:

With C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
int n = nums.size();
vector<int> map;
for(int i=0;i<n;i++)
{
for(int j=(i+1);j<n;j++)
{
if(nums[i]+nums[j]==target)
{ map.push_back(i);
map.push_back(j);
}
}
}
return map;
}
};

With Python:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

n = len(nums)
for i in range(n-1):
for j in range(i+1,n):
if (nums[i] + nums[j] == target):
return [i,j]

See my 30+ solutions of LeetCode on GitHub