leetcode 1.Two Sum (水题,STL_map)

来源:互联网 发布:'中国网络墙 编辑:程序博客网 时间:2024/06/08 14:14


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

题意:找出数组中的两个元素和为target,返回下标


class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        map<int,int>f;        vector<int>res;        int n = nums.size();        for(int i=0;i<n;i++) {            if(f.count(target-nums[i])) {                res.push_back(f[target-nums[i]]);                res.push_back(i);                return res;            }            f[nums[i]]=i;        }    }};