Why didnt call sort in my program???


  • 0
    Z

    call std::sort(nums.begin(), nums.end()); or sort(nums.begin(), nums.end(),cmp);

    all compiler failed,

    i dont know what's wrong?

    who can help.

    class Solution {
    public:
    struct Elem
    {
    int index;
    int num;
    bool operator<(const struct Elem &other)
    {
    return num < other.num;
    }
    };
    bool cmp(const struct Elem &a, const struct Elem &b)
    {
    return a.num < b.num;
    }
    bool binary_search(vector<Elem>&nums, int l, int r, int tar, int &index)
    {
    int low = l;
    int high = r;
    while(low <= high)
    {
    int mid = low + (high-low)/2;
    if (nums[mid].num == tar)
    {
    index = mid;
    return true;
    }
    else if (nums[mid].num < tar)
    {
    low = mid + 1;
    }
    else
    {
    high = mid - 1;
    }
    }
    return false;
    }
    vector<int> twoSum(vector<int> &numbers, int target) {
    vector<Elem>nums;
    nums.reserve(numbers.size());
    for (int i = 0; i < numbers.size(); ++ i)
    {
    Elem elem;
    elem.index = i + 1;
    elem.num = numbers[i];
    nums.push_back(elem);
    }

        std::sort(nums.begin(), nums.end());
        vector<int>res;
        for (int i = 0; i < nums.size() - 1; ++ i)
        {
            int tarIndex;
            if(binary_search(nums, i + 1, nums.size()-1, target - nums[i].num, tarIndex))
            {
                
                if (nums[i].index < nums[tarIndex].index)
                {
                    res.push_back(nums[i].index);
                    res.push_back(nums[tarIndex].index);
                }
                else
                {
                    res.push_back(nums[tarIndex].index);
                    res.push_back(nums[i].index);
                }
                break;
            }
        }
        
        return res;
    }
    

    };


  • 0
    S

    I think the compile error occured because you lost the header file including and the namespace definition.And "std::sort" is a quicklySort which is not stable,may it cause any indexing problems?


Log in to reply
 

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