您的位置:首页 > 职场人生

leetoj two sum

2015-07-09 21:52 387 查看
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

这道题目的意思是给出目标值,求数组中那两个数加起来等于目标值,求索引

1.暴力求解:用双重循环来求

for(int i=0;i<numbers.size();i++)
{
for(int j=i+1;j<numbers.size();j++)
{
if(numbers[i]+numbers[j]==target)
{
index1=i;
index2=j;
}
}
}


算法的时间复杂度为O(n^2),超时

2.先对数组进行排序,然后每次遍历一个数字,使用二分查找(O(log n))来寻找数组中是否存在target-numbers[i]这个数值,有的话就可以得出结果

//下面的代码是不完善的代码
Arrays.sort(numbers);
for(int i=0;i<numbers.size();i++)
{
int temp=target-numbers[i];
int k=bianry_search(temp);
index1=temp;
index2=k;
.......
}


当然假如在c语言中的话需要写出快排的函数,时间复杂度为O(NlogN)

3.第三种思想主要是参考第二种思想,但是不使用二分查找

首先我要对数组进行排序,然后我使用两个指针,一个指针指向第一个元素,另一个指针j指向最后一个元素j

那么

1.numbers[i]+numbers[j]

boolean hasSum(int[] A, int target)
{
boolean res=false;
if(A==null || A.length<2) return res;
Arrays.sort(A);
int i=0,j=A.length-1;
while(i<j)
{
if(A[i]+A[j]==target)
{
res=true;
break;
}
else if(A[i]+A[j]>target)
{
j--;
}
else i++;
}
return res;
}


时间复杂度还是O(NlogN)

4.通过使用哈希表来降低查询差值的时间复杂度,这里要记住的是 哈希表的查找是常数时间,所以程序的时间复杂度还是O(N),空间复杂度为哈希表的大小

class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> result;//
map<int,int> mp;
map<int,int>::iterator it;
int index1,index2;
for(int i=0;i<numbers.size();i++)
{
mp[numbers[i]]=i+1;
//cout<<numbers[i]<<endl;
}
for(int i=0;i<numbers.size();i++)
{
it=mp.find(target-numbers[i]);
if(it!=mp.end())
{
index1=i+1;
index2=it->second;
if(index1==index2) continue;
break;
}
}
int temp;
if(index1>index2)
{
temp=index1;
index1=index2;
index2=temp;

}
result.push_back(index1);
result.push_back(index2);
return result;
}
};


第一道leetoj上面的题目,也是第一道使用纯c++样式来做的oj题目,继续努力。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题 面试