1. 程式人生 > >LeetCode1 二數和

LeetCode1 二數和

class Solution {
private:
    struct package{
        public:
            int num;
            int pos;
            //package(int _num,int _pos):this->num(_num),this->pos(_pos){}
            package(int _num,int _pos):num(_num),pos(_pos){}
            
    };
public:
    vector<int> twoSum
(vector<int>& nums, int target) { vector<int> res; int first=0; int second=nums.size()-1; vector<package> vt; for(int i=0;i<nums.size();i++){ package temp(nums[i],i); vt.push_back(temp); } sort(vt.
begin(),vt.end(),[](package p1,package p2)->bool { return p1.num<p2.num; }); while(first<=second){ if(vt[first].num+vt[second].num>target) second--; if(vt[first].num+vt[second].num<target) first++; if(vt[first].num+vt[second]
.num==target){ res.push_back(vt[first].pos); res.push_back(vt[second].pos); return res; } } } };

時間複雜度 O(nlogn+n)
在這裡插入圖片描述