leetcode 1 Two Sum(查找)
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更快。
class Solution {
public:
struct node{
node(int i,int v):id(i),val(v){}
int id,val;
};
static bool cmp(node a,node b){
return a.val<b.val;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<node>vt;
vector<int>ans;
vector<int>::iterator it;
int a1=,a2=;
for(it=nums.begin();it!=nums.end();it++){
vt.push_back(node(++a1,*it));
}
sort(vt.begin(),vt.end(),cmp);
a1=;
for(it=nums.begin();it!=nums.end();it++){
int t=*it;
a1++;
a2=lower_bound(vt.begin(),vt.end(),node(,target-t),cmp)-vt.begin();
int a3=upper_bound(vt.begin(),vt.end(),node(,target-t),cmp)-vt.begin();
if(a2<vt.size()&&a2==a3&&vt[a2].val==target-t&&vt[a2].id>a1){
a2=vt[a2].id;
//printf("index1=%d, index2=%d\n",a1,a2);
ans.push_back(a1);
ans.push_back(a2);
return ans;
}
else if(a2<vt.size()&&vt[a2].val==target-t&&a2<a3){/*这个处理很有必要,不然[0,4,3,0]和target=0
这组数据会WA,二分时要注意考虑有几个相等的情况*/
for(int i=a2;i<a3;i++){
if(vt[i].id>a1){
ans.push_back(a1);
ans.push_back(vt[i].id);
return ans;
}
}
}
}
return ans;
}
};
my answer
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 = ; 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] + );
result.push_back(i + );
return result;
} //number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
better answer in discuss
leetcode 1 Two Sum(查找)的更多相关文章
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [LeetCode] 1. Two Sum 两数和
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- [LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
Design and implement a TwoSum class. It should support the following operations:add and find. add - ...
- [LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...
- Java for LeetCode 216 Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
- [leetCode][013] Two Sum 2
题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- [array] leetcode - 39. Combination Sum - Medium
leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...
随机推荐
- python获取shell输出(转)
From:http://www.cnblogs.com/snow-backup/p/5035792.html python中获取shell命令输出的方法: 1. import subproces ...
- 图像处理之基础---傅立叶c实现
http://blog.csdn.net/lzhq28/article/details/7847047 http://blog.csdn.net/lishizelibin/article/detail ...
- saltstack之定时管理
1.设置定时任务 /srv/salt/cron/ntpdate.sls /usr/sbin/ntpdate 10.31.10.3; /sbin/hwclock -w: cron.present: - ...
- ASIHTTP
本文转载至 http://www.th7.cn/Program/IOS/201303/128223.shtml 向服务器端上传数据 ASIFormDataRequest ,模拟 Form表单提 ...
- [Matlab绘图][三维图形][三维曲线基本函数+三维曲面+其他三维图形]
1.绘制三维图形的基本函数 最基本的三维绘图函数为plot3: plot3与plot用法十分相似,调用格式: plot(x1,y1,z1,选项1,x2,y2,z2,选项2,...,xn,yn,zn,选 ...
- hdu_吃糖果(思维题)
吃糖果 Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submiss ...
- windy数(简单数位DP)
1026: [SCOI2009]windy数 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 6306 Solved: 2810[Submit][Sta ...
- The hidden layers are either convolutional, pooling or fully connected.
https://en.wikipedia.org/wiki/Convolutional_neural_network Convolutional layers apply a convolution ...
- ShowModal 代码分析
下面为Delphi中,方法TCustomForm.ShowModal的代码,通过分析以下代码,可以了解ShowModal到底是怎么一回事! 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
- sublime 添加 注释插件 Docblockr
https://github.com/spadgos/sublime-jsdocs Package Control Open Package Control: Preferences -> Pa ...