题目分析
这道算法题存在两种情况,数组中是否存在相同的值
1、给定一个整型数组,找出其中的两个数使其和等于指定的值,并返回两个数的数组下标(假定是无序数组,数组元素各不相同)
2、给定一个整型数组,找出其中的两个数使其和等于指定的值,并返回两个数的数组下标(假定存在相同的数)
解题思路
1、假设数组元素各不相同
采用哈希表存储整型数组,key为数组元素,value为元素下标,查找的时间复杂度为O(n),需要检查结果不是相同的两个数。
2、假设数组元素存在相同值
使用改进的哈希表存储整型数组,key为数组元素,value为元素下标和元素出现次数的结构体,需要检查目标值是否是两个相同的值,当目标值不是两个相同值时,查找的时间复杂度为O(n)。
c++代码
数组元素各不相同的情况
//buffer 整型数组
//length 数组长度
//target 目标值
//result 结果
bool GetTwo1(int* buffer,int length,int target,int result[])
{
if(buffer == NULL || length < 2)
{
return false;
}
hash_map<int,int> hashMap;
hashMap.clear();
result[0] = -1;
result[1] = -1;
//转换成hashmap存储
for(int i = 0; i < length; i++)
{
hashMap.insert(pair<int,int>(buffer[i],i));
}
//搜索是否存在两个值的和等于目标值
int one = 0;
int two = 0;
for(int i = 0; i < length; i++)
{
one = buffer[i];
two = target - one;
if(hashMap.find(two) != hashMap.end() && target != two*2)
{
result[0] = i;
result[1] = hashMap[two];
return true;
}
}
return false;
}
数组元素存在相同值的情况
struct Result
{
//元素下标
int index;
//数组中改元素个数
int count;
};
bool GetTwo2(int* buffer,int length,int target,int result[])
{
if(buffer == NULL || length < 2)
{
return false;
}
hash_map<int,Result> hashMap;
hashMap.clear();
result[0] = -1;
result[1] = -1;
Result hash_value;
//转换成hashmap存储
for(int i = 0; i < length; i++)
{
hash_value.index = i;
hash_value.count = 1;
if(hashMap.find(buffer[i]) != hashMap.end())
{
hashMap[buffer[i]].count += hash_value.count;
}
else
{
hashMap.insert(pair<int,Result>(buffer[i],hash_value));
}
}
//搜索是否存在两个值的和等于目标值
int one = 0;
int two = 0;
for(int i = 0; i < length; i++)
{
one = buffer[i];
two = target - one;
if(hashMap.find(two) != hashMap.end())
{
//判断目标值是否是两个相同值之和
if(!(target == two*2 && hashMap[two].count == 1))
{
if(target == two*2)
{
result[0] = i;
for(int j = i+1; j < length; j++)
{
if(buffer[j] == two)
{
result[1] = j;
return true;
}
}
}
else
{
result[0] = i;
result[1] = hashMap[two].index;
return true;
}
}
}
}
return false;
}
测试代码
数组元素各不相同的情况
int buffer[10] = {4,3,1,5,2,6,7,8,9,10};
int result[2] = {-1,-1};
cout<<"please input a target that equals sum of two data from buffer"<<endl;
int target = 0;
cin>>target;
bool isExist = GetTwo1(buffer,10,target,result);
cout<<"is exist :"<<isExist<<" the result is "<<result[0]<<" , "<<result[1]<<endl;
cout<<"please input a target that not equals sum of two data from buffer"<<endl;
cin>>target;
isExist = GetTwo1(buffer,10,target,result);
cout<<"is exist :"<<isExist<<" the result is "<<result[0]<<" , "<<result[1]<<endl;
数组存在相同值的情况
int buffer[10] = {4,3,1,5,4,6,4,8,9,10};
int result[2] = {-1,-1};
cout<<"please input a target that equals sum of two data from buffer"<<endl;
int target = 0;
cin>>target;
bool isExist = GetTwo2(buffer,10,target,result);
cout<<"is exist :"<<isExist<<" the result is "<<result[0]<<" , "<<result[1]<<endl;
cout<<"please input a target that not equals sum of two data from buffer"<<endl;
cin>>target;
isExist = GetTwo2(buffer,10,target,result);
cout<<"is exist :"<<isExist<<" the result is "<<result[0]<<" , "<<result[1]<<endl;