Two Sum
2017-03-27 13:48
99 查看
问题描述:Two Sum
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. 暴力穷举
思路:开始的时候我打算用python的itertools库中的combinations函数来直接生成所有的组合,然后再判断是否等于target,如果等于返回这组数,然后再用list的index函数返回i坐标。但这个思路出现了一个问题,给定的list中出现重复的元素时,用index返回坐标会只返回前面的坐标。于是我打算用暴力穷举来实现这个算法。
代码:
复杂度:当然这里使用了两层循环,时间复杂度是O(n2) ,空间复杂度是O(1) 。
2. map
思路:为了减少时间复杂度,我采用map来存储value和index,这样一来,我们就可以在O(1)内找到index了。当然把元素放到map中会耗费我们O(n)的复杂度。
代码:
复杂度:时间复杂度O(n),空间复杂度O(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. 暴力穷举
思路:开始的时候我打算用python的itertools库中的combinations函数来直接生成所有的组合,然后再判断是否等于target,如果等于返回这组数,然后再用list的index函数返回i坐标。但这个思路出现了一个问题,给定的list中出现重复的元素时,用index返回坐标会只返回前面的坐标。于是我打算用暴力穷举来实现这个算法。
代码:
class Solution { 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 (nums[j] == target - nums[i]) { a.push_back(i); a.push_back(j); return a; } } } } };
复杂度:当然这里使用了两层循环,时间复杂度是O(n2) ,空间复杂度是O(1) 。
2. map
思路:为了减少时间复杂度,我采用map来存储value和index,这样一来,我们就可以在O(1)内找到index了。当然把元素放到map中会耗费我们O(n)的复杂度。
代码:
#include<map> class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> a; vector<int> result; for(int i = 0 ; i < nums.size() ; i++) { a[nums[i]] = i; } for(int i = 0 ; i < nums.size() ; i++) { int b = target - nums[i]; map<int,int>::iterator it; it = a.find(b); if(a.count(b) && it->second != i) { result.push_back(i); result.push_back(it->second); return result; } } } };
复杂度:时间复杂度O(n),空间复杂度O(1)。
相关文章推荐
- [LeetCode] Two Sum
- leetcode -- Two Sum
- LeetCode-Two Sum
- Two Sum 数组中找两个之和为sum@LeetCode
- LeetCode:Two Sum
- LeetCode 001 Two Sum
- LeetCode Two Sum
- 【LeetCode】Two Sum
- Two Sum
- Leetcode 线性表 Two Sum
- leetcode之Two Sum
- 【LeetCode with Python】 Two Sum
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- [LeetCode]Two Sum
- Two Sum[leetcode]
- Leetcode-Two Sum
- [LeetCode]Two Sum 【Vector全局指针的使用】
- LeetCode[Hash Table]: Two Sum
- 和大神们学习每天一题(leetcode)-Two Sum
- 1 Two Sum