您的位置:首页 > 其它

LeetCode之1—-Two Sum

2016-03-27 15:08 323 查看
题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

题目大意:

给定一个数组和一个目标值,返回数组中两个数字加起来等于该目标值的下标。

思路:很容易想到暴力求解法,时间复杂度是O(n^2),因为题目的Tag是easy,所以抱着试试的态度试了试。。。。结果可想而知。。。超时!!

#include <iostream>
#include <cstdlib>
#include <vector>

class Solution {
public:
std::vector<int> twoSum(std::vector<int> &nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
for (int j = 0; j < nums.size(); ++j) {
if (i == j) {
continue;
} else {
if (nums[i] + nums[j] == target) {
v.push_back(i);
v.push_back(j);
break;
}
}
}
if (v.size() != 0) {
break;
}
}
return v;
}

private:
std::vector<int> v;
};

int main(int argc, char *argv[])
{
std::vector<int> nums({2, 7, 11, 15});
int target = 9;

Solution s;
std::vector<int> v = s.twoSum(nums, target);

for (auto a : v) {
std::cout << a << " ";
}
std::cout << std::endl;

return EXIT_SUCCESS;
}


看来得另辟蹊径了。超时的原因是时间复杂度太高,降低时间复杂度的方法就是使用hash来降低查找的次数从而达到降低时间复杂度的目的。由于使用C++语言进行编程,所以自然而然就想到了使用map容器来将数字和target建立联系。这里可以使用数组的元素值来表示map的key,使用数组的下标作为map的value,达到在O(1)时间迅速查找到对应值的下标。所以可以将时间复杂度降低到O(n)。

代码:

class Solution {
public:
std::vector<int> twoSum(std::vector<int> &nums, int target) {

for (int i = 0; i < nums.size(); ++i) {
tmp[nums[i]] = i;
}

for (int i = 0; i < nums.size(); ++i) {
if (tmp.find(target - nums[i]) != tmp.end() && i != tmp[target - nums[i]]) {
v.push_back(i);
v.push_back(tmp[target- nums[i]]);
break;
}
}

return v;
}

private:
std::vector<int> v;
std::map<int, int> tmp;
};
  

好吧,AC是AC了可是效率还是不高,28ms,比起效率最高的4ms差距好大好大!!!好吧。。。再优化一下吧,经过思考发现上边的两个for语句可以合并成一个for语句,这样的话在一些特殊情况下可以减少循环的次数。所以就有了以下的代码,运行效率比之前少了4ms。然而还是离4ms差距好大!!!然而我并没有在答案里边找到4ms的方法,大多数高赞方法都是运行都是答案错误。可能是因为问题的边界检查更新了的缘故吧。

  
class Solution {
public:
std::vector<int> twoSum(std::vector<int> &nums, int target) {

/*for (int i = 0; i < nums.size(); ++i) {
tmp[nums[i]] = i;
}
*/
for (int i = 0; i < nums.size(); ++i) {
if (tmp.find(target - nums[i]) != tmp.end() && i != tmp[target - nums[i]]) {
v.push_back(tmp[target- nums[i]]);
v.push_back(i);
break;
} else {
tmp[nums[i]] = i;
}
}

return v;
}

private:
std::vector<int> v;
std::map<int, int> tmp;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: