Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have e... ...
Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
- 直接一個排序,O(nlgn),然後一個查找,O(n)
- 使用unordered_map
代碼
O(nlgn)的解法
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; int len = nums.size(); if(len == 0) return res; vector<pair<int, int>> vec; for(int i = 0; i < len; ++i){ vec.push_back(pair<int, int>(nums[i], i)); } sort(vec.begin(), vec.end(), [](const pair<int, int> &a, const pair<int, int>&b){ return a.first < b.first;}); int i = 0, j = len - 1, tmp; while(i < j){ tmp = vec[i].first + vec[j].first; if(tmp == target){ res.push_back(min(vec[i].second, vec[j].second)); res.push_back(max(vec[i].second, vec[j].second)); break; } else if(tmp < target) i++; else j--; } return res; } };
O(n)的解法
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; int len = nums.size(); if(len == 0) return res; unordered_map<int, int> hash; int needToFind = 0; for(int i = 0; i < len; ++i){ needToFind = target - nums[i]; if(hash.find(needToFind) != hash.end()){ res.push_back(min(i, hash[needToFind])); res.push_back(max(i, hash[needToFind])); break; } else{ hash.insert(pair<int, int>(nums[i], i)); } } return res; } };