Question:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Anwser 1: O(n*m)
- class Solution {
- public:
- vector<int> twoSum(vector<int> &numbers, int target) {
- vector<int> ret(2, 0);
- int len = numbers.size();
- for(int i = 0; i < len; i++)
- {
- int tmp = target - numbers[i]; //another number
- for(int j = i + 1; j < len; j++)
- {
- if(tmp == numbers[j])
- {
- ret[0] = i + 1;
- ret[1] = j + 1;
- return ret;
- }
- }
- }
- return ret;
- }
- };
Anwser 2: O(n*log(n))
- typedef struct node{
- int idx;
- int val;
- node(){};
- node(int i, int v) : idx(i), val(v){}
- }Node;
- bool compare(const Node& a, const Node& b){
- return a.val < b.val;
- }
- class Solution {
- public:
- vector<int> twoSum(vector<int> &numbers, int target) {
- int len = numbers.size();
- assert(len >= 2);
- vector<int> ret(2, 0);
- vector<Node> nums(len);
- for(int i = 0; i < len; i++){
- nums[i] = Node(i+1, numbers[i]);
- }
- sort(nums.begin(), nums.end(), compare);
- int l = 0;
- int r = len - 1;
- while(l < r){
- int sum = nums[l].val + nums[r].val;
- if(sum == target){
- ret[0] = min(nums[l].idx, nums[r].idx); // val is compare, but idx not
- ret[1] = max(nums[l].idx, nums[r].idx);
- break;
- } else if(sum < target){
- l++;
- } else {
- r--;
- }
- }
- return ret;
- }
- };
Anwser 3: 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;
- vector<long long> mul(len, 0);
- for(int i = 0; i < len; i++){
- mul[i] = (target - numbers[i]) * numbers[i];
- if(mapping[mul[i]] > 0){
- if(numbers[i] + numbers[mapping[mul[i]] - 1] == target){
- ret[0] = mapping[mul[i]];
- ret[1] = i + 1;
- break;
- }
- } else {
- mapping[mul[i]] = i + 1;
- }
- }
- return ret;
- }
- };