1.Two Sum

今晚看完天下足球之后,在leetcode上最一道题,于是选择了第一道题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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

看完这道题,第一想法是用两层for循环来解决,于是提交了如下代码:


class Solution{
public:
vector<int> twoSum(vector<int>& nums, int target) {
      int right = 0;
      int left = 0;
      int flag = 1;
      vector<int> result ;
    
      //sort( nums.begin(), nums.end(), cmp );
      for( ; right < nums.size() && flag ; right++ )
        for( left = right + 1; left < nums.size() && flag; left++ )
        {
          cout<<"nums["<<right<<"] = "<<nums[right]<<endl;
          cout<<"nums["<<left<<"] = "<<nums[left]<<endl;
          if( nums[right] + nums[left] == target )
          {
            cout<<"nums["<<right<<"] = "<<nums[right]<<endl;
            cout<<"nums["<<left<<"] = "<<nums[left]<<endl;
            result.push_back( right );
            result.push_back( left );
            flag = 0;
          }
        }
      return result;
    }
};


但是当在网站上提交之后,发现程序运行的效果并不是很好,然后,通过在网上查找,发现可以用map来解决该问题,于是自己写了如下的代码:

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

通过该段代码回想其C++中map的使用方法,尤其是insert()方法。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值