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].
Related Topics:
Array, Hash Table
Similar Questions:
- 3Sum (Medium)
- 4Sum (Medium)
- Two Sum II - Input array is sorted (Easy)
- Two Sum III - Data structure design (Easy)
- Subarray Sum Equals K (Medium)
- Two Sum IV - Input is a BST (Easy)
- Two Sum Less Than K (Easy)
// Problem: https://leetcode.com/problems/two-sum/
// Author: github.com/ankuralld5999
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
vector<int> twoSum(vector<int>& A, int target) {
vector<vector<int>> v;
int N = A.size(), L = 0, R = N - 1;
for (int i = 0; i < N; ++i) v.push_back({ A[i], i });
sort(begin(v), end(v), [](const vector<int> &a, const vector<int> &b) { return a[0] < b[0]; });
while (L < R) {
int sum = v[L][0] + v[R][0];
if (sum == target) return { v[L][1], v[R][1] };
if (sum < target) ++L;
else --R;
}
return {};
}
};
// Problem: https://leetcode.com/problems/two-sum/
// Author: github.com/ankuralld5999
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> twoSum(vector<int>& A, int target) {
unordered_map<int, int> m;
for (int i = 0; i < A.size(); ++i) {
int t = target - A[i];
if (m.count(t)) return { m[t], i };
m[A[i]] = i;
}
return {};
}
};