Ошибка сегментации11: в этом вопросе сортировки и поиска - PullRequest
0 голосов
/ 04 апреля 2020

вопрос: Учитывая массив целых чисел, вернуть индексы двух чисел так, чтобы они складывались до заданной цели c.

решение -

  • копирование сумм в cpy
  • сортировка cpy для последующего бинарного поиска
  • итерация cpy
  • поиск цели - current_no.
  • если присутствует в cpy
  • получить индексы в исходных номерах векторов
  • добавить индексы в вектор результатов и вернуть вектор результатов
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

        vector<int>cpy;
        vector<int>result(2);
        result[0] = 0;
        result[1] = 0;

        int indx = 0;
        for(indx = 0; indx < nums.size(); ++indx)
        {
            cpy[indx] = nums[indx];
        }

        // sorting to enable binary search on vector later on
        sort(cpy.begin(), cpy.end());


        int x, y;
        bool ispresent;
        vector<int>:: iterator base1;
        vector<int>:: iterator it2;
        base1 = nums.begin();

        for(indx = 0; indx < cpy.size(); ++indx)
        {
            x = cpy[indx];
            y = target - x;

            // sing bin search to make search time faster
            ispresent = binary_search(cpy.begin() + indx, cpy.end(), y);

            if(ispresent)
            {
                cout << "found" << endl;
                // fiding index of x, y in original vector nums
                result[0] = find(nums.begin(), nums.end(), x) - base1;
                result[1] = find(find(nums.begin(), nums.end(), x) + 1, nums.end(), y) - base1;
                break;
            }
        }
        return result;
    }

};

int main()
{
    int n;
    cin >> n;

    vector<int> v(n);
    for(int i = 0; i < n; ++i)
    {
        cin >> v[i];
    }

    int target;
    cin >> target;

    Solution ob;

    vector<int>res = ob.twoSum(v, target);
    cout << res[0] << " " << res[1] << endl;

    return 0;
}

1 Ответ

2 голосов
/ 04 апреля 2020

Простой, вы записываете значения в ваш cpy вектор, но он имеет нулевой размер.

Существует очень простой способ скопировать векторы, просто используйте =.

vector<int> cpy = nums;

Это все, что вам нужно. Вам не нужно написанное вами для l oop.

...