1. Two Sum

来源:互联网 发布:mac os 9.2弹出u盘 编辑:程序博客网 时间:2024/06/14 12:49

刚开始学习C++。试着刷一下Leetcode,第一个月先把easy搞定吧。

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

方法一

简单粗暴,直接用两个循环将向量遍历一遍,将符合目标值的数下标返回

class Solution

{

public:

vector<int>  twosum(vector<int> &nums,int target)

  {

      vector  <int>  res;

      int size=nums.size();

     for(int i=0;i<size;i++)

          { 

              for(int j=i+1;j<size;j++)

                      {

                         if(nums[j]==target-nums[i])

                                        vec.push_back(i);

                                        vec.push_back(j);

                        return res;

                    }

           }

return res;

  }

};

方法二:

创建一个hash表,unordered_map<int,int>,存储的是nums[i],i;

然后自己再检查是否在map中是否存在target-nums[i],将下表返回

class Solution

{

public:

vector<int> twosum(vector<int> &nums,int target)

     {

          vector<int> res;

         int size=nums.size();

         unordered_map<int,int>  m;

         for(int i=0;i<size;i++)

              {

                      if(m.count(target-nums[i]))

                 {               res.push_back(i);

                                res.push_back(m.[target-nums[i]]);

                       return res;

                 }

                       m[nums[i]]=i;

              }

                  return res;

     }

};