leetcode刷题,我的解法1 twosum问题

struct node{
    int num,pos;
};
bool cmp(node a,node b){
    return a.num<b.num;
}
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
           vector<node> copy; //定义node类型的矢量,赋值的时候也是node类型整体赋值,用pushback函数
        vector<int> result;
        for(int i=0;i<numbers.size();++i){
            node t;
            t.num=numbers[i];
            t.pos=i;
            copy.push_back(t);
        }
        sort(copy.begin(),copy.end(),cmp);//得到排序后保存index的复制数组
        //进行查找
        int low,high;
            low=0;
            high=numbers.size()-1;
        while(low!=high){
            int sum=copy[low].num+copy[high].num;
            if(sum>target)
                high--;
            else if(sum<target)
                low++;
            else if(sum==target){
                if(copy[low].pos<copy[high].pos){
                result.push_back(copy[low].pos+1);
                result.push_back(copy[high].pos+1);
                break;//开始没有加,提示超出内存限制,就是无限循环了
                }
                else{
                result.push_back(copy[high].pos+1);//这个地方犯过错,直接返回high和low了
                result.push_back(copy[low].pos+1);  
                break;
                }
            }
            
        }
        return result;
    }
};
需要注意while的结束条件!!
另一种方法
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
           vector<int> result;
           map<int,int> copy;
           //给map赋值
           for(int i=0;i<numbers.size();++i){
               copy[numbers[i]]=i;
           }
           map<int,int>::iterator j=copy.end();//存的是找到的结果,也可以单独设置指针存储?
           for(int i=0;i<numbers.size();++i){
             j=copy.find(target-numbers[i]);
             if(j!=copy.end()&&i<j->second){
               result.push_back(i+1);
               result.push_back(j->second+1);
               break;
             }
             else if(j!=copy.end()&&i>j->second){
               result.push_back(j->second+1);
               result.push_back(i+1);
               break;
             }
           }
           return result;
    }
};

<p style="margin: 10px auto;">很容易忘记的是:map中元素的查找:</p><p style="margin: 10px auto;">   find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。        </p><p style="margin: 10px auto;">   map<int ,string >::iterator l_it;; 
   l_it=maplive.find(112);
   if(l_it==maplive.end())
                cout<<"we do not find 112"<<endl;
   else cout<<"wo find 112"<<endl;</p>

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值