题目:
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.
样例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
答案:
简单遍历vector就行了,size*size复杂度,本来想先排序,再遍历,但是排序需要记录排序前和排序后索引的对应关系。
代码:


1 #include <algorithm> 2 3 class Solution { 4 private: 5 static bool cmp(const int &a, const int &b) 6 { 7 return a < b; 8 } 9 10 public: 11 vector<int> twoSum(vector<int>& nums, int target) { 12 // std::sort(nums.begin(),nums.end(),cmp); 13 14 int i,j; 15 int size = nums.size(); 16 int rest; 17 vector<int> ans; 18 19 for(i = 0; i < size; ++ i) 20 { 21 rest = target - nums[i]; 22 for(j = i + 1;j < size; ++ j) 23 { 24 if(rest == nums[j]) 25 { 26 ans.push_back(i); 27 ans.push_back(j); 28 return ans; 29 } 30 } 31 } 32 } 33 };
本文详细解析了一道经典算法题“两数之和”的解决方案,通过遍历数组找到两个数,使它们的和等于特定的目标值。文章提供了一个简单但效率较低的O(n^2)算法实现,适用于初学者理解和掌握基本的算法思想。
368

被折叠的 条评论
为什么被折叠?



