1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.


image.png
  • 算法思想:
    暴力循环,从第一个元素开始,逐个遍历其后所有元素,若遇到与符合要求的元素,将两个元素的下标值存入 vector 并返回
  • C++ Solution
vector twoSum(vector& nums, int target) {
    vector indice;
    for(int i = 0; i < nums.size(); ++i) {
        for(int j = i+1; j < nums.size(); ++j) {
            if(nums[i] + nums[j] == target) {
                indice.push_back(i);
                indice.push_back(j);
                break;
            }
        }
    }
    return indice;
}
  • 时间复杂度为O(n)的另一种解法
vector twoSum(vector &nums, int target)
{
    //Key is the number and value is its index in the vector.
    unordered_map hash;
    vector result;
    for (int i = 0; i < nums.size(); i++) {
        int numberToFind = target - nums[i];

            //if numberToFind is found in map, return them
        if (hash.find(numberToFind) != hash.end()) {
            result.push_back(hash[numberToFind]);
            result.push_back(i);            
            return result;
        }

            //number was not found. Put it in the map.
        hash[nums[i]] = i;
    }
    return result;
}

你可能感兴趣的:(1. Two Sum)