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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目的意思不理解,求数组中是否存在两个数之和等于给定的数,并且返回两个数的下标,注意返回的是下标,而且从给定的结果来看要求下标的顺序和数字在数组中出现的顺序相对应。
首先一个直接的思路就是穷举,代码如下:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 int size=nums.size(); 5 vector<int> result; 6 for(int i=0;i<size-1;i++) 7 { 8 for(int j=i+1;j<size;j++) 9 { 10 if(nums[i]+nums[j]==target) 11 { 12 result.push_back(i); 13 result.push_back(j); 14 } 15 16 } 17 } 18 19 return result; 20 } 21 };
可以AC,但是时间复杂度为O(n^2),需要改进
如果题目只要求返回数字,可以考虑使用sort直接对原来的向量进行排序,然后放置一头一尾两个指针解决问题,时间复杂度O(n*logn)
这道题最直接的思路是构建hash表,利用map容器完成,代码如下:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 map<int, int> hash; 5 vector<int> result; 6 for (int i = 0; i < nums.size(); i++) { 7 int numberToFind = target - nums[i]; 8 if (hash.find(numberToFind) != hash.end()) { 9 result.push_back(hash[numberToFind]); 10 result.push_back(i); 11 return result; 12 } 13 14 //number was not found. Put it in the map. 15 hash[nums[i]] = i; 16 } 17 return result; 18 } 19 };
一刷(2018.01.25):各种出错,忘记target减去nums[i],忘记push_back(hash[numberToFind])