1.Leetcode1 Two Sum

题目: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].
我的解决方法1:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        vector<int>::iterator iter;
        int position;
        for(int i=0;i<nums.size();i++)
        {
            iter=std::find(nums.begin(),nums.end(),(target-nums[i]));
            position=std::distance(nums.begin(),iter);
            if(iter!=nums.end() && position!=i)
            {
                result.push_back(i);
                result.push_back(position);
                break;
            }
        }   
         return result;
    }
};

我的解决方法2:
借助map映射实现,基础知识参考我的博客

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int,int> mapping;
        for(int i=0;i<nums.size();i++)
            mapping[nums[i]]=i;
        for(int i=0;i<nums.size();i++)
        {
            int gap=target-nums[i];
            if(mapping.find(gap)!=mapping.end() && i!=mapping[gap])
            {
                result.push_back(i);
                result.push_back(mapping[gap]);
                    break;
            }
        }
        return result;
    }
};
全部评论

相关推荐

程序员鼠鼠_春招版:都很烂大街,rpc也基本没人问,考研吧,不然就包装一段实习再去
点赞 评论 收藏
分享
头发暂时没有的KFC总裁:找廉价劳动力罢了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务