您的位置:首页 > 其它

中山大学算法课程题目详解(第一周)

2017-09-10 19:12 239 查看

问题描述:

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, and you may not use the same element twice.


Example

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


解决方法:

拿到题目,还是很自然地想到用两层for循环进行暴力求解,具体代码如下:

vector<int> twoSum(vector<int>& nums, int target) {
vector<int> answer;
for (int i = 0; i < nums.size(); i++) {
int flag = target - nums[i];
for (int j = i + 1; j < nums.size(); j++) {
if (flag == nums[j]) {
answer.push_back(i);
answer.push_back(j);
break;
}
}
}
return answer;
}

发现leedcode网站其实还是给过的,其实这是一个O(n^2)时间复杂度的算法,一旦数据量变大,耗费的时间必定很长。

采用map减少时间复杂度
思路是循环一次,每次都判断当前数组索引位置的值在不在map里,不在的话,加入进去,key为数值,value为它的索引值;在的话,取得他的key,记为n(此时n一定小于循环变量i),接下来再在map中查找(target-当前数值)这个数,利用了map中查找元素时间为常数的优势,如果找到了就结束,此处需要注意的是,如果数组中有重复的值出现,那么第二次出现时就不会加入到map里了,比如3,4,3,6;target=6时,当循环到第二个3时,也可以得到正确结果。代码如下:

vector<int> twoSum(vector<int>& nums, int target) {
vector<int> answer;
map<int, int> hmap;
for (int i = 0; i < nums.size(); i++) {
if (!hmap.count(nums[i])) {
hmap.insert(pair<int, int>(nums[i], i));
}
if (hmap.count(target - nums[i])) {
int n = hmap[target - nums[i]];
if (n < i) {
answer.push_back(n);
answer.push_back(i);
return answer;
}
}
}
return answer;
}
时间复杂度是O(n),比上面的暴力求解法少了好多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: