1. The sum of two numbers

topic


Given an array of integers and a target value, find two numbers in the array that sum to the target value.

You can assume that each input corresponds to only one answer, and that the same elements cannot be reused.

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

solution


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int>result;
        map<int,int> temp;
        for(int i=0;i<nums.size();i++)
        {
            temp[nums[i]]=i;
        }
        for(int i=0;i<nums.size();i++)
        {
            //第一个条件判断是否有sum-first==two?,第二个条件判断first和two不能是同一个元素
            if(temp.find(target-nums[i])!=temp.end()&&i!=temp[target-nums[i]])
            {
                result.push_back(i);
                result.push_back(temp[target-nums[i]]);
                break;
            }
        }
        return result;
    }
};

ideas


The first time it is done is the violent solution, the time complexity is O(n²). This solution uses space to exchange time, reduces the time complexity to O(n), uses a map to store data, and the key is the value of numbers, value is the subscript of the value in numbers. Each time it is traversed, it is judged whether another number target-nums[i] exists, and if it exists, it can be returned (it is also necessary to judge that the two values ​​cannot be the same element).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324851029&siteId=291194637