LeetCode Two Sum
来源:互联网 发布:king网址软件 编辑:程序博客网 时间:2024/06/13 23:33
自己写的,运行28ms
vector<int> twoSum(vector<int> &numbers, int target) {// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.int i,j;vector<int> ret;for (i=0;i<numbers.size();i++){for (j=i+1;j<numbers.size();j++){if (numbers[i]+numbers[j]==target){ret.push_back(i);ret.push_back(j);return ret;}}}return ret;}别人的,先排序,运行16ms,内部排序时间应该是O(NlogN),http://blog.csdn.net/ju136/article/details/6975666
class node { public: int id; int value; public: node(int a, int b):id(a), value(b){} friend bool operator < (const node &a, const node &b) { return a.value < b.value;} }; vector<int> twoSum(vector<int> vs, int target) { const int s = vs.size(); vector<int> ret; vector<node> temp; for (int i = 0; i < s; ++i) temp.push_back(node(i+1, vs[i])); sort(temp.begin(), temp.end()); for (int b = 0, e = s - 1; b < e; ) { const int v = temp[b].value + temp[e].value; if (v == target) { if (temp[b].id < temp[e].id) { ret.push_back(temp[b].id); ret.push_back(temp[e].id); } else { ret.push_back(temp[e].id); ret.push_back(temp[b].id); } return ret; } else if (v < target) { ++b; } else --e; } return ret; }别人的,用map,时间也是16ms,因为map是用红黑树实现的,所以快在find算法了。http://blog.csdn.net/doc_sgl/article/details/12115067
vector<int> twoSum(vector<int> &numbers, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> res; int length = numbers.size();if(length < 2)return res;map<int,int> mp;for(int i = 0; i < length; ++i)mp[numbers[i]] = i;map<int,int>::iterator it = mp.end();for(int i = 0; i < length; ++i){it = mp.find(target - numbers[i]);if(it != mp.end()){res.push_back(min(i+1,it->second +1));res.push_back(max(i+1,it->second +1));break;}}return res; }题目说第一个索引要小于第二个(应该是小于等于),其实,这题当输入只有一个时候同样元素时,比如4,2,5,找8,算会输出同样的1,1。
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 【Android 开发】: Android 消息处理机制之一: Handler 与 Message
- 荷兰国旗问题 将3种数中重复数聚集 Sort Colors
- 数据库并发控制原理详解
- 手动8 -svn安装
- android系统之apn相关
- LeetCode Two Sum
- 第二节 页面跳转
- 安卓开发中菜单
- 在CentOS 6.4中编译安装gcc 4.8.1
- 获取当前路径
- C 语言之运算符
- iphone开发前传
- MySQL中的视图及性能问题
- linux用户管理