7: two sum
来源:互联网 发布:淘宝如何自己刷信誉 编辑:程序博客网 时间:2024/06/02 06:26
注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解
题目:Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解析1:用一个哈希表,存储每个数对应的下标,复杂度 O(n)
解题代码如下:
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mapping; // 数组nums 中的元素及对应下标 for (int i = 0; i != nums.size(); ++i) mapping[nums[i]] = i; for (int i = 0; i != nums.size(); ++i) { const int gap = target - nums[i]; if (mapping.find(gap) != mapping.end() && mapping[gap] > i) return vector<int>{i + 1, mapping[gap] + 1}; } }};
解析2:先排序然后左右夹逼,排序O(nlgn),左右夹逼O(n),总的时间是O(nlgn),但是这个方法返回的是下标,不是数字本身,因此不是本题的解法,但其代码如下:
//在一个数组中寻找两个数,使它们之和//等于 target//先将数组排序然后左右夹逼vector<vector<int>> twoSum(vector<int>& nums, const int target){ vector<vector<int>> result; if (nums.size() <= 1) return result; sort(result.begin(), sort.end()); auto first = result.begin(), last = result.end() - 1; while (first < last) { if (*first + *last < target) { ++first;// while (first < last && *(first - 1) == *(first))// ++first; } else if (target < *first + *last) { --last;// while (first < last && *(last + 1) == *last)// --last; } else { result.push_back(vector<int>{*first, *last}); ++first; --last; while (first < last && *first == *(first - 1)) ++first; while (first < last && *last == *(last + 1)) --last; } } return result;}
0 0
- 2.1.7 Two Sum
- 7: two sum
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- CF445B:DZY Loves Chemistry(并查集)
- JAVA蓝桥杯(3)猜算式
- VirtualBox中CentOS-7无法访问网络和putty无法连接问题
- Spring - Java/J2EE Application Framework 应用框架 第 15 章 EJB的存取和实现
- Vue 仿百度搜索
- 7: two sum
- Spring - Java/J2EE Application Framework 应用框架 第 16 章 通过Spring使用远程访问和web服务
- HDU 1257 最少拦截系统
- DOM遍历
- 传智168期JavaEE struts2杜宏 day32~day33(2017年2月15日23:25:00)
- Spring - Java/J2EE Application Framework 应用框架 第 17 章 使用Spring邮件抽象层发送Email
- HDU-1874畅通工程续(最短路问题)
- Linux中执行CakePHP Shell文件
- 走迷宫