中山大学算法课程题目详解(第一周)
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),比上面的暴力求解法少了好多
相关文章推荐
- 中山大学算法课程题目详解(第十四周)
- 中山大学算法课程题目详解(第十八周)
- 中山大学算法课程题目详解(第十三周)
- 中山大学算法课程题目详解(第十九周)NP问题
- 中山大学算法课程题目详解(第七周)
- 中山大学算法课程题目详解(第四周)
- 中山大学算法课程题目详解(第十一周)
- 中山大学算法课程题目详解(第十五周)
- 中山大学算法课程题目详解(第十二周)
- 中山大学算法课程题目详解(第五周)
- 中山大学算法课程题目详解(第六周)
- 中山大学算法课程题目详解(第十六周)
- 中山大学算法课程题目详解(第十周)
- 中山大学算法课程题目详解(第三周)
- 中山大学算法课程题目详解(第十七周)
- 算法设计与应用基础-第一周题目
- 算法第一周:HashMap有关题目
- 算法课程Leetcode作业第一周技术博客
- 精选微软经典的算法面试100题(第1-20题) -代码详解(题目选自“结构之法”大侠的博客,答案都是本菜鸟自己做的)
- 【python数据挖掘课程】二十.KNN最近邻分类算法分析详解及平衡秤TXT数据集读取