1. Two Sum
2016-06-12 11:12
330 查看
题目:
https://leetcode.com/problems/two-sum/
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.
1. 最直接实现,冒泡法,两两相加。(算法复杂度o(n*n)不能通过)
c++实现方法
2. 使用map实现,算法复杂度o(n*logn)
C++实现
python实现
对代码做些优化
4. 先排序,再前后杂遍历, 时间复杂度o(n*logn + n)
算法复杂度偏高,题目要求把初始位置记录起来,比较麻烦,就没实现。
https://leetcode.com/problems/two-sum/
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.
1. 最直接实现,冒泡法,两两相加。(算法复杂度o(n*n)不能通过)
c++实现方法
vector<int> twoSum(vector<int>& vec, int target) { vector<int>::iterator it; for(it=vec.begin();it!=vec.end();it++){ vector<int>::iterator it2; for(it2=it+1;it2!=vec.end();it2++){ if(*it + *it2 == target){ vector<int> re; re.push_back(it-vec.begin()); re.push_back(it2-vec.begin()); return re; } } } return vector<int>(); }
2. 使用map实现,算法复杂度o(n*logn)
C++实现
vector<int> twoSum(vector<int>& vec, int target) { map<int ,int>mapTarget; for(int i = 0; i < vec.size(); i++){ if(mapTarget.find(vec[i]) != mapTarget.end()){ vector<int> re; re.push_back(mapTarget.find(vec[i])->second); re.push_back(i); return re; } mapTarget.insert(pair<int,int>(target - vec[i], i)); } return vector<int>(); }3. 使用 hash_map来存值,算法复杂度 o(n)
python实现
def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ ret_map = {} for i, num in enumerate(nums): index = ret_map.get(target - num, None) if index is None: ret_map[num] = i else: return [ret_map[target - num], i]
对代码做些优化
def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ ret_map = {} for i, num in enumerate(nums): if target - num in ret_map: return [ret_map[target - num], i] ret_map[num] = i
4. 先排序,再前后杂遍历, 时间复杂度o(n*logn + n)
算法复杂度偏高,题目要求把初始位置记录起来,比较麻烦,就没实现。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 关于指针的一些事情
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例