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
Subscribe to see which companies asked this question
Show Similar Problems
这种题目就是注意转换下标和值
#include <iostream> #include <vector> using namespace std; class IndexData { public: IndexData(){} int index; int value; }; /* * 1.生成一个vector,并对vector的 value 进行排序 * 2.两个指针,left, right, left < right * 3.如果 vector[left][1] + vector[right][1] > value, right--; * 4.如果 vector[left][1] + vector[right][1] < value, left--; * 5.如果 == , 返回, 注意返回index 的大小 * */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<IndexData*> v_data; vector<int> res; size_t num_size = nums.size(); size_t i = 0; for (; i<num_size; i++) { IndexData* d = new IndexData(); d->index = i; d->value = nums[i]; v_data.push_back(d); } sort(v_data.begin(), v_data.end(), cmp); int left = 0; int right = num_size - 1; while (left < right) { while ((left < right) && ((v_data[left]->value + v_data[right]->value) > target)) { right--; } while ((left < right) && ((v_data[left]->value + v_data[right]->value) < target)) { left++; } if ((v_data[left]->value + v_data[right]->value) == target) { if(v_data[left]->index < v_data[right]->index) { res.push_back(v_data[left]->index + 1); res.push_back(v_data[right]->index + 1); } else { res.push_back(v_data[right]->index + 1); res.push_back(v_data[left]->index + 1); } break; } } for (i=0; i<num_size; i++) { if (NULL != v_data[i]) { delete v_data[i]; v_data[i] = NULL; } } return res; } private: static bool cmp(const IndexData* id1, const IndexData* id2) { return id1->value < id2->value; } }; int main() { vector<int> v; v.push_back(3); v.push_back(2); v.push_back(4); Solution s; s.twoSum(v, 6); return 0; }
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ res_list = [] new_nums = list(enumerate(nums)) new_nums.sort(key = lambda x:x[1]) left = 0 right = len(new_nums) - 1 while left < right: while new_nums[left][1] + new_nums[right][1] > target and left < right: right = right - 1 while new_nums[left][1] + new_nums[right][1] < target and left < right: left = left + 1 if new_nums[left][1] + new_nums[right][1] == target and left < right: index_1 = new_nums[left][0] + 1 index_2 = new_nums[right][0] + 1 if index_1 < index_2: res_list.append(index_1) res_list.append(index_2) else: res_list.append(index_2) res_list.append(index_1) left = left + 1 right = right - 1 return res_list
posted on 2015-12-30 23:01 walkwalkwalk 阅读(214) 评论(0) 编辑 收藏 举报