Leetcode解题笔记 1.Two Sum [Easy]
2017-09-11 10:07
387 查看
解题思路
本题属于leetcode简单题,题目要求找到能构成目标整形数的两个数字在vector里的位置,设定是必然能找到可匹配的两个数,所以不用做错误检测,而且只是两个数相加,所以只需要判断下每个数与target的差是否存在于vector中就可以了。代码
我在代码里面用到了map,简化编程流程,一开始想得好复杂,想着会有多个数去相加,这样可能要用到树壮结构,但考虑到题目叫作two sum,两个数相加,所以其实并不需要往多个数相加去把问题复杂化。第一次用leetcode,还自己写了个输入输出的测试,其实是多余的..
#include <iostream> #include <vector> #include <map> using namespace std; vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; map<int, int> mymap; map<int, int>::iterator iter; for (int i = 0; i < nums.size(); i++) { int sub = target - nums[i]; iter = mymap.find(sub); if (iter != mymap.end()) { result.push_back(iter->second); result.push_back(i); break; } else { mymap.insert(pair<int, int>(nums[i], i)); } } return result; } int main(int argc, const char * argv[]) { vector<int> vec; int target; int n; cin >> n; int temp; for (int i = 0; i < n; i++) { cin >> temp; vec.push_back(temp); } cin >> target; vector<int> result = twoSum(vec, target); for (int i = 0; i < result.size(); i++) { cout << result[i] << ' '; } cout << endl; return 0; }
时间复杂度
O(n): 因为最多只会扫一次。相关文章推荐
- leetcode解题笔记:Two sum系列解题思路
- LeetCode解题报告 1. Two Sum[easy]
- LeetCode个人笔记-Two Sum(1)
- 菜鸟写给菜鸟的 ——LeetCode解题笔记 Easy-题目2:258. Add Digits
- LeetCode刷题笔记(Two Sum)
- [leetcode] 1. Two Sum 解题报告
- leetcode解题报告(22):Two Sum II - Input array is sorted
- Leetcode 1. Two Sum (Easy) (cpp)
- [Leetcode] 1. Two Sum 解题报告
- 【LeetCode】599.Minimum Index Sum of Two Lists(Easy)解题报告
- Leetcode解题笔记 2.Add Two Numbers [Medium]
- 【LeetCode】1.Two Sum解题报告
- Leetcode解题笔记121. Best Time to Buy and Sell Stock [Easy] 动态规划
- 【LeetCode】1. Two Sum 解题报告
- 【LeetCode】TwoSum解题报告
- LeetCode解题笔记349 Intersection of Two Arrays
- 【Leetcode】Two sum(easy)
- leetcode解题方案--167--Two Sum II - Input array is sorted
- leetcode解题系列:Two Sum
- Leetcode解题笔记 70. Climbing Stairs [Easy] 动态规划