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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
First Method: two pointers.
vector<int> twoSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end()); // suppose the input array is not sorted.
if(nums.size() < 2) return {};
int forward = 0;
int backward = nums.size() - 1;
while(forward < backward) {
int sum = nums[forward] + nums[backward];
if(sum == target) {
return {forward, backward};
} else if(sum > target) {
backward--;
} else {
forward++;
}
}
} // in this case, time complexity is O(nlgn)... space is O(1)
Second Method: use hashMap
// if the input is not sorted.
vector<int> twoSumII(vector<int>& nums, int target) {
unordered_map<int, int> dataToIndex;
for(int i = 0; i < nums.size(); ++i) {
auto iter = dataToIndex.find(target - nums[i]);
if(iter == dataToIndex.end()) {
dataToIndex.insert(make_pair(nums[i], i));
} else {
return {i, iter->second};
}
}
} // time complexity O(n), space complexity O(n).
Variation:
Input is a binary search tree, find two sum.
bool twoSum(TreeNode* root, int target) {
int val_1 = 0, val_2 = 0;
stack<TreeNode*> leftHalf;
stack<TreeNode*> rightHalf;
bool leftSide = false, rightSide = false;
while(1) {
TreeNode* leftNode = root;
while(leftSide == false) {
if(leftNode) {
leftHalf.push(leftNode);
leftNode = leftNode->left;
} else {
if(leftHalf.empty()) leftSide = true;
else {
TreeNode* tmp = leftNode.top();
leftNode.pop();
val_1 = tmp->val;
leftNode = leftNode->right;
leftSide = true;
}
}
}
TreeNode* rightNode = root;
while(rightSide == false) {
if(rightNode) {
rightHalf.push(rightNode);
rightNode = rightNode->right;
} else {
if(rightHalf.empty()) rightSide = true;
else {
TreeNode* tmp = rightNode.top();
rightNode.pop();
val_2 = tmp->val;
rightNode = tmp->left;
rightSide = true;
}
}
}
if(val_1 != val_2 && target = val_1 + val_2) return true;
else if(val_1 + val_2 < target) leftSide = false;
else rightSide = false;
if(val_1 >= val_2) return false;
}
}