1 Two Sum

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].

Solution:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        int n = nums.size();
        if ( n <= 1 ) return res;
        map<int, int> record;
        for ( int i = 0; i <= n-1; i++ ) {
            // if ( record.find(target - nums[i]) == record.end() ) record[nums[i]] = i;
            if ( record.find(target - nums[i]) == record.end() ) {
                record.insert(pair<int, int>(nums[i], i));
            }
            else {
                res.push_back(record[target - nums[i]]);
                res.push_back(i);
                return res;
            }
        }
        return res;
    }
};

Notes
Two ways to insert an element to a map:

// use insert
record.insert(pair<int, int>(nums[i], i));
// set the value
record[nums[i]] = i

results matching ""

    No results matching ""