LeetCode Two Sum

 

题目描述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

大意:两个参数,一个vector int,一个int target,寻找a+b=target(题目中最后一句每个target都会有一个结果,说明必然存在),返回a,b的索引,并不是a,b的value。

 

解题思路:1,用到map容器,这样就能将key value和index联系起来,返回满足条件的两个index

        2,遍历整个numbers即可

代码部分:
 
class Solution {
public:
    vector
   
   
    
     twoSum(vector
    
    
     
      &numbers, int target) {
        vector
     
     
      
       b;
        map
      
      
       
        ma;
        map
       
       
         ::iterator it; /* for(int i=0;i 
        
          second+1); b.push_back(i+1); return b; } // it=ma.find(numbers[i]); // if(it==ma.end()) else ma[numbers[i]]=i; } */ for(int i=1;i 
         
           second); b.push_back(i+1); return b; } } } }; 
          
         
       
      
      
     
     
    
    
   
   

 

代码分析:

1,题目已经排除了numbers中有相等值的情况了,例如【4,4,1】,5,此时就会有问题。You may assume that each input would have exactly one solution.

2,注释掉的是参考别人的代码,思路就是从第一个开始遍历,找到就返回,找不到,就判断遍历到的该值是否存在,map不存在就存入。直到找到。

3, 其实没必要判断遍历到的numbers【i】是否存在,因为如果找不到target-numbers【i】,那么就应该将numbers【i】存入,因为每个numbers都不等

4,遍历的过程中,可以先存,再检查(就是代码中的for循环);也可以先检查,再存(注释掉的部分);不同点:先存入的话,就从numbers【1】开始;先检查的话就从numbers【0】开始。归根到底一样的,因为从0开始检查的话,也是先存了numbers【0】,接着检查的target-numbers【1】;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值