1. Two Sum (Easy)

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

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

Solution: Hash Table

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> m;
    for (int i = 0; i < nums.size(); ++i) {
        int numToFind = target-nums[i];
        if (m.count(numToFind)) return {m[numToFind], i};
        m[nums[i]] = i;
    }
    return {};
}

Follow Up:

Determine whether two of the numbers add up to x, without using Hash Table

Solution: Two Pointers

Time Complexity: $$O(nlogn)$$

class Solution {
public:
    bool twoSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int left = 0, right = nums.size()-1;
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum == target) return true;
            else if (sum < target) ++left;
            else --right;
        }
        return false;
    }
};

results matching ""

    No results matching ""