Day one
Given an array of integers nums
and a target value target
, and you figure out a target value of the two integers in the array, and return to their array subscript.
You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice .
Example:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
c++
Here is a high praise problem solution, and its mistakes have been corrected
Violence law:
Because the same element in the array can not be used twice, so there is no similar [2,2,3,4],target=6
circumstances
But do not rule out [2,5,3,4],target=7
the case, then the default is looking to return to the first answer
After thinking about the two problems above, then start thinking about solutions
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j;
for(i=0;i<nums.size()-1;i++)
{
for(j=i+1;j<nums.size();j++)
{
if(nums[i]+nums[j]==target)
{
return {
i,j};
}
}
}
return {
};
};
};
Summary: The method is simple but the time complexity is O(n 2 ). Space complexity is O(1),
slow running speed and large memory space consumption
Two-pass hash table:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a;//建立hash表存放数组元素
vector<int> b(2,-1);//存放结果
for(int i=0;i<nums.size();i++)
a.insert(map<int,int>::value_type(nums[i],i));
for(int i=0;i<nums.size();i++)
{
if(a.count(target-nums[i])>0&&(a[target-nums[i]]!=i))
//判断是否找到目标元素且目标元素不能是本身
{
b[0]=i;
b[1]=a[target-nums[i]];
break;
}
}
return b;
};
};
A hash table
Improvement: While iterating and inserting elements into the table, we will also go back and check whether the target element corresponding to the current element already exists in the table. If it exists, then we have found the corresponding solution and return it immediately.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a;//提供一对一的hash
vector<int> b(2,-1);//用来承载结果,初始化一个大小为2,值为-1的容器b
for(int i=0;i<nums.size();i++)
{
if(a.count(target-nums[i])>0)
{
b[0]=a[target-nums[i]];
b[1]=i;
break;
}
a[nums[i]]=i;//反过来放入map中,用来获取结果下标
}
return b;
};
};