首页 > 代码库 > [LeetCode]Two Sum
[LeetCode]Two Sum
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:利用map
// TwoSum2.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <vector>#include <map>using namespace std;class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { map<int, int>numMap; vector<int>res; map<int, int>::iterator map_lt; for (int i = 0; i < numbers.size(); i++) { numMap[numbers[i]] = i; } for (int i = 0; i < numbers.size(); i++) { map_lt = numMap.find(target - numbers[i]); if (map_lt != numMap.end() && numMap[target - numbers[i]] != i) { res.push_back(i+1); res.push_back(numMap[target - numbers[i]]+1); break; } } return res; }};int _tmain(int argc, _TCHAR* argv[]){ vector<int>nums; nums.push_back(2); nums.push_back(7); nums.push_back(11); nums.push_back(15); Solution ss; vector<int>res = ss.twoSum(nums,9); cout << res[0] << " " << res[1] << endl; system("pause"); return 0;}
解法2:先排序,然后前后2个指针
// TwoSum.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <vector>#include<iostream>#include <algorithm>using namespace std;class Node{public: int num; int pos;};bool cmp(Node a, Node b){ return a.num < b.num;}class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<Node>arrays; vector<int>res; for (int i = 0; i < numbers.size(); i++) { Node tempNode; tempNode.num = numbers[i]; tempNode.pos = i; arrays.push_back(tempNode); } sort(arrays.begin(),arrays.end(),cmp); int i, j; for (i = 0, j = arrays.size() - 1; i != j;) { if (arrays[i].num + arrays[j].num == target) { int min, max; max = arrays[i].pos >= arrays[j].pos ? arrays[i].pos : arrays[j].pos; min = arrays[i].pos <= arrays[j].pos ? arrays[i].pos : arrays[j].pos; res.push_back(min+1); res.push_back(max+1); break; } else if (arrays[i].num + arrays[j].num > target) { j--; } else if (arrays[i].num + arrays[j].num < target) { i++; } } return res; } };int _tmain(int argc, _TCHAR* argv[]){ Solution ss; vector<int>nums; nums.push_back(2); nums.push_back(7); nums.push_back(11); nums.push_back(15); vector<int>res = ss.twoSum(nums, 9); cout << "index1=" << res[0] << ", index2=" << res[1] << endl; system("pause"); }
[LeetCode]Two Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。