Accepted c++ solution with a pointer array


  • 2
    T
    bool cmpptr(int *p1, int *p2){
        return *p1 < *p2;
    }
    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int *> pNums;
            for(auto &num:numbers){
                pNums.emplace_back(&num);
            }
            sort(pNums.begin(), pNums.end(), cmpptr);
            vector<int> result;
            int s(0), e(pNums.size() - 1);
            while(s < e){
                int twoSum = *pNums[s] + *pNums[e];
                if(twoSum == target){
                    int idx1 = pNums[s] - &numbers[0] + 1;
                    int idx2 = pNums[e] - &numbers[0] + 1;
                    if(idx1 > idx2) swap(idx1, idx2);
                    result= {idx1, idx2};
                    break;
                }else if(twoSum < target){
                    ++s;
                }else{
                    --e;
                }
            }
            return result;
        }
    };

  • 2

    what's the meaning of this (这个什么意思)
    for(auto &num:numbers){
    pNums.emplace_back(&num);
    }


  • 0
    T

    It can be replaced with "for(int i = 0; i < numbers.size(); ++i){
    pNums.push_back(&numbers[i]);
    }"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.