leetcode-【简单题】Two Sum

题目

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 };
View Code
原文地址:https://www.cnblogs.com/Shirlies/p/5211829.html