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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        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;     // +1 for not zero-based
                    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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        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);    // O(n*log(n))
        
        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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int len = numbers.size();
        assert(len >= 2);           
        
        vector<int> ret(2, 0);
        
        map<int, int> mapping;              // default all are 0
        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){        // not default 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;    // larger than 0
            }
        }
        
        return ret;
    }
};

 

Anwser 4:  O(n)  in  Java  ( time is more longer and longer than C++)

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int len = numbers.length;
        assert(len >= 2);
        
        int[] ret = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        for(int i = 0; i < len; i++){
            if( !map.containsKey(numbers[i]) ){
                map.put(target - numbers[i], i);        // save another number
            }
            
            if( map.containsKey(numbers[i]) ){          // check is another number
                int idx = map.get(numbers[i]);
                if(idx < i){
                    ret[0] = idx + 1;   // +1 for not zero-based
                    ret[1] = i + 1;
                }
            }
        }
        
        return ret;
    }
}

 

 

参考推荐:

cplusplus_sort

Leetcode Questions

 

原文: 【leetcode】TwoSum