Leetcode--TwoSum

双指针 and 排序:

bool lessthan(const pair& lhs,const pair& rhs){
    if(lhs.first == rhs.first)
        return lhs.second < rhs.second;
    return lhs.first < rhs.first;
}

class Solution {
public:
    vector twoSum(vector& numbers, int target) {

    vector> vnum;
    for (size_t i = 0; i < numbers.size() ; ++i){
        vnum.push_back(make_pair(numbers[i],i));
    }
    sort(vnum.begin(),vnum.end(),lessthan);
    vector  result;

    int s = 0;
    int e = vnum.size()-1;

    while(s < e){
        if(vnum[s].first + vnum[e].first == target){
            result.push_back(min(vnum[s].second,vnum[e].second));
            result.push_back(max(vnum[s].second,vnum[e].second));
            break;
        }
        else if (vnum[s].first + vnum[e].first > target)
            e -= 1;
        else
            s += 1;
    }
    return result;
        
    }
};


你可能感兴趣的:(Leetcode--TwoSum)