【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
相关文章推荐
- Python 刷题日记:LeetCode: 1&15&16-Two Sum and 3Sum
- leetcode 1. Two Sum python
- 1.Two Sum Leetcode Python
- 【leetcode】4. Median of Two Sorted Arrays(Python & C++)
- Leetcode 1. Two Sum(python)
- leetcode two sum python
- [LeetCode] Two Sum Python 题解
- Leetcode_two-sum (c++ and python version)
- leetcode 167. Two Sum II - Input array is sorted python
- LeetCode 1 — Two Sum(C++ Java Python)
- Leetcode-Python 1 .Two Sum/ 7. Reverse Integer
- [Leetcode][python/java]Two Sum/Two Sum II
- 【leetcode】160. Intersection of Two Linked Lists(Python & C++)
- LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum
- [leetcode]Two Sum C++ python实现
- leetcode 1.Twosum python
- 1. Two Sum Leetcode Python New season for 2016
- Python学习——leetcode(Two Sum)
- Two Sum Leetcode Python Java
- leetcode two sum python 实现