题目:
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
题目说明:
就是在一个数组里面找两个数,这两个数的和等于target的值。
可能出现的坑
- vector的长度是一个坑,考虑为0为1的情况。
- 数组中可能会出现两个一样的数,比如numbers=[0,1,4,5,0] ;target=0这种情况。如果使用map以value为key存储的话,只能保存一个。map不支持多个键值。
以下是我的两种做法,均AC。
第一种方法使用了map,用来发现当前探索的值的另一半(target-current)是否存储了。若已经存储,则返回。若为存储,则加入map。复杂度为O(n)。代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> index;
if( (nums.size() == 0) || (nums.size() == 1) )
return index;
map<int,int> value_index;
for(int i = 0;i < nums.size();i++)
{
int current_value = nums[i];
if(value_index.count(target - current_value) == 1)
{
index.push_back(value_index[target - current_value] + 1);
index.push_back(i+1);
return index;
}
else
{
value_index[current_value] = i;
}
}
return index;
}
};
第二种方法使用了结构体,并对结构体数组进行排序。从两边到中间的进行查找。时间复杂度主要用于排序,复杂度为O(nlogn)。代码如下:
struct value_index
{
int value;
int index;
};
bool compare(value_index a,value_index b)
{
return a.value < b.value;
}
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> index;
if( nums.size() <= 1 )
return index;
vector<value_index> value_index_array(nums.size());
for(int i = 0; i < nums.size();i++)
{
value_index_array[i].value = nums[i];
value_index_array[i].index = i;
}
sort(value_index_array.begin(),value_index_array.end(),compare);
int begin_index = 0;
int end_index = value_index_array.size() - 1;
while(begin_index != end_index)
{
if(value_index_array[begin_index].value + value_index_array[end_index].value < target)
{
begin_index++;
}
else if(value_index_array[begin_index].value + value_index_array[end_index].value > target)
{
end_index--;
}
else
{
int index1 = value_index_array[begin_index].index;
int index2 = value_index_array[end_index].index;
int bigger = index1 > index2 ? index1 : index2;
int smaller = index1 + index2 - bigger;
index.push_back(smaller + 1);
index.push_back(bigger + 1);
return index;
}
}
return index;
}
};