Two Sum
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
这个题目很简单,不过我首先想到思路很简单,效率不高。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> twonum;
for(int i = 0; i <nums.size();++i){
for(int j = i+1; j<nums.size(); ++j){
if(nums[i]+nums[j] == target){
twonum.push_back(i+1);
twonum.push_back(j+1);
return twonum;
}
}
}
}
};第二种思路也比较容易想到:
因为第一种方法,时间复杂度主要在两个for循环上面,所以如果想降低时间复杂度必须从两个for循环入手;第一个for循环应该少不了吧(起码我目前认为是这样),第二个for循环其实降低它的时间复杂度;因为可以对target-nums[i]的值进行二分查找,如果能够找到,则ok;
第三种方法是用STL的算法find来查找target-nums[i];不过该算法的时间复杂度没有二分查找低;
下面首先是algorithm中find算法的实现源码:
template<class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
while (first!=last) {
if (*first==val) return first;
++first;
}
return last;
}class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> twonum;
vector<int>::iterator pos1, pos2;
for(pos1 = nums.begin(); pos1 != nums.end(); ++pos1){
pos2 = find(pos1+1, nums.end(), target-(*pos1));
if(pos2 != nums.end()){
twonum.push_back(pos1-nums.begin()+1);
twonum.push_back(pos2-nums.begin()+1);
return twonum;
}
}
}
};肯定还会有时间复杂度更低的实现算法,如果知道的话以后再补上;感觉如果使用的查找算法好的话,那么该算法一定会好;
第一种的运行时间见下图:
第二种的运行时间如下:
为什么别人的运行时间都这么少啊。目前想不到比较好的算法。以后知道了再更新;
本文讨论了如何在一个整数数组中找到两个数,它们的和等于给定的目标数,并提供了多种解决方案,包括使用双层循环、二分查找和STL算法的find函数。详细分析了每种方法的时间复杂度,并通过运行实例展示了不同方法的实际执行时间对比。
291

被折叠的 条评论
为什么被折叠?



