Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目不难理解,都能写的出来,关键看效率,我最先想到的就是俩for循环嵌套,来实现,和大神比简直弱爆了!大神定义一个很长的数组(0Xffff),用数组指针,把数值转换成指针的移位,比如数值是35,那就把数组指针移位35,并赋值为35,用这种方式来构建类似hashMap的功能,效率没的说(leedcode Runtime: 8 ms),但在空间上,可能会浪费不少空间。以空间换时间的做法是否值得,不知是否可取。
入门级:
vector<int> twoSum1(vector<int>& nums, int target) {//leedcode Runtime: 620 ms
int temp = 0;
vector<int> result;
for (int i = 0; i < nums.size(); i++){
temp = target - nums[i];
for (int j = i + 1; j < nums.size(); j++){
if (temp == nums[j]){
result.push_back(i + 1);
result.push_back(j + 1);
}
}
}
return result;
}
高手级:
vector<int> twoSum3(vector<int>& nums, int target) {//leedcode Runtime: 24 ms
map<int, int> IntHash;
int temp = 0;
vector<int> result;
//for (int i = 0; i < nums.size(); i++)
//{
// IntHash[nums[i]] = i;
//}
for (int i = 0; i < nums.size(); i++)
{
temp = target - nums[i];
if (IntHash.find(temp) != IntHash.end()){
result.push_back(IntHash[temp] + 1);
result.push_back(i + 1);
return result;
}
else
{
IntHash[nums[i]] = i;
}
}
return result;
}
大神级:
vector<int> twoSum4(vector<int>& nums, int target) {//leedcode Runtime: 8 ms
vector<int> result;
int valueIndices[0Xffff] = { 0 };
//int valueIndicesN[0xffff] = {0};
for (size_t i = 0; i != nums.size(); ++i)
{
int value = target - nums[i];
if (valueIndices[value + 0Xffff / 2] != 0)
{
result[0] = valueIndices[value + 0Xffff / 2];
result[1] = i + 1;
break;
}
else
{
if (valueIndices[nums[i] + 0Xffff / 2] == 0)
{
valueIndices[nums[i] + 0Xffff / 2] = i + 1;
}
}
}
return result;
}