Solution:1. hashmap, O(n). | 2. sort first. O(nlog n) | ||||||
vector<int> twoSum(vector<int> &numbers, int target) { map<int,int> myMap; vector<int> ret; for (int i=0;i<numbers.size();i++) { if(myMap.count(numbers[i])==0) myMap[numbers[i]]= i; if(myMap.count(target-numbers[i])) { int l=myMap[target-numbers[i]]; if(l<i) { ret.push_back(l+1); ret.push_back(i+1); return ret; } } } } //sort method, by anniekim bool compare(pair<int, int> a, pair<int, int> b) { return a.first < b.first; } vector<int> twoSum(vector<int> &numbers, int target) { vector<pair<int, int>> nums(numbers.size()); for (int i = 0; i < numbers.size(); ++i) nums[i] = make_pair(numbers[i], i+1); sort(nums.begin(), nums.end(), compare); int l = 0, r = nums.size() - 1; while (l < r) { int sum = nums[l].first + nums[r].first; if (sum == target) break; else if (sum < target) l++; else r--; } vector<int> res; res.push_back(min(nums[l].second, nums[r].second)); res.push_back(max(nums[l].second, nums[r].second)); return res; } |
Tuesday, September 30, 2014
two sum
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment