1. 两数之和
为保证权益,题目请参考 1. 两数之和(From LeetCode).
解决方案1
CPP
C++
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
vector<int> ans;
map<int, int> maps;
for (unsigned i = 0; i < nums.size(); ++i)
{
if (maps.find(target - nums[i]) != maps.end())
{
ans.push_back(maps[target - nums[0]]);
ans.push_back(i);
return ans;
}
else
{
maps.insert(map<int, int>::value_type(nums[i], i));
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Python
python
# 1. 两数之和
# https://leetcode-cn.com/problems/two-sum/
################################################################################
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
################################################################################
if __name__ == "__main__":
solution = Solution()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21