leetcode 1 Two Sum(查找)
2015-10-17 16:56
483 查看
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
solution:暴力算法很显然是O(n2)会超时。
那么我的做法是把数组排序后二分查找。这样是O(n*lgn)。这里注意一个细节是类内的cmp比较函数要定义成静态成员函数,不然sort调用时会报错:invalid use of non-static member function。因为非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。
还有discuss里有更好的O(n)算法,就是hash的思想,利用unordered_map这一无序map来使查找的时间接近常数。unordered_map和map的区别是它无序,所以在不需要排序时最好使用它,比map更快。
better answer in discuss
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
solution:暴力算法很显然是O(n2)会超时。
那么我的做法是把数组排序后二分查找。这样是O(n*lgn)。这里注意一个细节是类内的cmp比较函数要定义成静态成员函数,不然sort调用时会报错:invalid use of non-static member function。因为非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。
还有discuss里有更好的O(n)算法,就是hash的思想,利用unordered_map这一无序map来使查找的时间接近常数。unordered_map和map的区别是它无序,所以在不需要排序时最好使用它,比map更快。
vector<int> twoSum(vector<int> &numbers, int target) { //Key is the number and value is its index in the vector. unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < numbers.size(); i++) { int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them if (hash.find(numberToFind) != hash.end()) { //+1 because indices are NOT zero based result.push_back(hash[numberToFind] + 1); result.push_back(i + 1); return result; } //number was not found. Put it in the map. hash[numbers[i]] = i; } return result; }
better answer in discuss
相关文章推荐
- 从源码角度理解android动画Interpolator类的使用
- 从源码角度理解android动画Interpolator类的使用
- 从源码角度理解android动画Interpolator类的使用
- 大道至简
- opencv3版本在线参考文档
- UFT工具
- Apache服务免安装版配置
- 从源码角度理解android动画Interpolator类的使用
- css实现多行文本溢出显示省略号(…)全攻略
- 网站优化
- 第一章 关于对象
- POJ 3368 Frequent values
- hibernateTemplte 问题
- 字典树(Trie)的java实现
- http://fir.im免费发布内测版app和用企业版证书发布app
- javascript 案例(二)表格操作(下)
- 20151017数组计算学生考试成绩
- cmake生成eclipse工程的调试问题
- NDK基本数据类型及操作
- OPENCV篇——第五章 图像的简单处理