AK_HuangYC的博客

人一我十,人十我百

leetcode 1.Two Sum (水题,STL_map)


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;
        }
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/h1021456873/article/details/78248061
个人分类: Leetcode
想对作者说点什么? 我来说一句

Leetcode two sum java 解法

2014年03月13日 537B 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭