这么著名的题目都没见过,算法小白要努力了!
Two sum即给出一组数,找出其中两个之和为某一特定值的索引。
python:
def findTwoSum(inputList, sumOfTwo):
aimDic = dict()
result = [-1, -1]
for num in inputList:
if num in aimDic.keys():
#返回找到的两个值
#result[0]=aimDic[num]
#result[1]=num
#返回找到的两个值的序号
result[0] = inputList.index(aimDic[num])
result[1] = inputList.index(num)
print("find two: ",result[0], result[1])
return result
else:
aimDic[sumOfTwo - num] = num
print("NOT find two sum!")
return result
if __name__ == "__main__":
rst = findTwoSum([1,5,3,7,2,9,6,11], 18)
C语言:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//用hash表解决在给定的一列数中找到两个之和为某一给定值得问题
int *sumTwo(int *numList, int len, int target)
{
if(numList == NULL)
{
printf("number list is null\n");
return NULL;
}
int min=2147483647,i=0,hashLen=0;
int * hashTbl = NULL;
int * index = (int *)malloc(2*sizeof(int)); //存放输出结果
//找到最小数,用来确定hash表长度
for(i=0;i<len;i++)
{
if(min > numList[i])
min = numList[i];
}
if(min == 2147483647)
{
printf("the input number may invalid\n");
return NULL;
}
hashLen= target-min+1;
printf("hashLen:%d\n",hashLen);
hashTbl = (int *)malloc(hashLen*sizeof(int));
//初始化hash表
for(i=0;i<hashLen;i++)
{
hashTbl[i]=-1;
}
for(i=0;i<len;i++)
{
//printf("target-numList[i]=%d\n",target-numList[i]);
if((target-numList[i]>0)&&(hashTbl[target-numList[i]] != -1))
{
index[0]=hashTbl[target-numList[i]];
index[1]=i;
printf("i=%d,index:%d,%d\n",i,index[0],index[1]);
return index;
}
else
hashTbl[numList[i]]=i;
//printf("hashTbl[%d]=%d\n",numList[i],i);
}
printf("fail to find two sum is equal to target\n");
return NULL;
}
int main () {
clock_t clockStart,clockEnd; //用于计算程序运行时间
double cost;
clockStart=clock();
printf("hello https://tool.lu/\n");
int nums[]={2,14,5,6,10,15,8,9,3,11,7};
int sum=16;
int lenInput=sizeof(nums)/sizeof(nums[0]);
printf("lenInput:%d\n",lenInput);
int *twoIndex=sumTwo(nums,lenInput,sum);
if(twoIndex!=NULL)
{
free(twoIndex);
twoIndex=NULL;
}
clockEnd=clock();
cost=(double)(clockEnd-clockStart)/CLOCKS_PER_SEC;
printf("clockStart:%ld,clockEnd:%ld,cost %ld seconds\n",clockStart,clockEnd,cost);
return 0;
}