Two Sum Leetcode 解法实现
2014-03-22 16:41
316 查看
这道题不难,只要用对工具的话,下面是时间复杂度为o(n)的解法,具体如下:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { int len = numbers.size(); assert(len >= 2); vector<int> ret(2, 0); map<int, int> mapping; // default all are 0 for(int i=0;i<len;i++) { if(mapping[target-numbers[i]]) { ret[0]=mapping[target-numbers[i]]; ret[1]=i+1; break; } else { mapping[numbers[i]]=i+1; } } return ret; } };时间复杂度为o(nlogn)的解法如下所示:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { int i,j; vector<int> a; int n=numbers.size(); int sum=0; int flag[100000][2]; for(i=0;i<n;i++) { flag[i][0]=numbers[i]; flag[i][1]=i+1; } sort(numbers.begin(),numbers.end()); i=0;j=n-1; while(i<j) { sum=numbers[i]+numbers[j]; if(sum>target) { j--; } else if(sum==target) { break; } else { i++; } } // printf("%d %d\n",i,j); int k,p,q,fok1=0,fok2=0,count=0; for(k=0;k<n;k++) { if(count==2) break; else { if(flag[k][0]==numbers[i]&&fok1==0) { p=flag[k][1]; count++; fok1=1; } else if(flag[k][0]==numbers[j]&&fok2==0) { q=flag[k][1]; count++; fok2=1; } } } if(p>q) { a.push_back(q); a.push_back(p); } else { a.push_back(p); a.push_back(q); } return a; } };
相关文章推荐
- [leetcode]leetcode第一题 1. Two Sum java O(n)解法
- LeetCode 之 Two Sum — C++ 实现
- LeetCode ---- Two Sum (Java Lua 实现)
- LeetCode[1] Two Sum (java实现)
- Leetcode平台上的TwoSum题目用Java哈希表实现
- [leetcode] Sum of Two Integers--用位运算实现加法运算
- LeetCode-1-Two Sum(C语言实现)
- LeetCode(1) Two Sum实现
- leetcode刷题,我的解法1 twosum问题
- LeetCode Two Sum 之 JavaScript 多种解法
- [leetcode]Two Sum C++ python实现
- leetcode 371 Sum of Two Integers java实现
- [LeetCode] Sum of Two Integers(用位运算实现加法)
- LeetCode twosum C++ map实现
- leetcode[Minimum Index Sum of Two Lists]//待整理多种解法
- leetcode two sum python 实现
- [LeetCode][1]Two Sum解析 -Java实现
- leetcode-Two sum(最佳思路以及python代码实现)
- javascript实现leetcode之two sum
- leetcode[Two Sum IV - Input is a BST]//待整理多种解法