题目描述:
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].
题解:
题目的参数是一个vector和一个target,要求我们返回一个新的vector,新vector的内容保存初始vector中某两个元素加起来等于target的下标。(这里使用C++实现)
解法1(蛮力算法,时间复杂度O(n^2):循环遍历vector,然后记录两个符合条件的元素下标。
class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {vector<int>result;for(int i=0;i<nums.size();i++){for(int j=i+1;j<nums.size();j++){if(nums[i]+nums[j]==target){result.push_back(i);result.push_back(j);}}}return result;}};
解法2(多使用一个哈希表作为记录,时间复杂度O(n)):在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,将其返回。
PS:这里为什么选择哈希表而不适用数组,是因为查找的时候哈希表的效率比数组快,在查询表中是否已经存在元素的时候,哈希表只需要o(1)的时间复杂度,而数组要o(n)。所以如果使用数组的话,时间复杂度和蛮力算法实际上是一样的。
class Solution {
public:vector<int>twoSum(vector<int>& nums, int target) {map<int,int>result;vector<int>v;for(int i=0;i<nums.size();i++){int temp = target-nums[i];if(result.find(temp)!= result.end()){v.push_back(result[temp]);v.push_back(i);}result[nums[i]]=i;}return v;}
};