diff --git a/Algorithms/Sorting/closest-numbers.cpp b/Algorithms/Sorting/closest-numbers.cpp index f303ccf..354a82a 100644 --- a/Algorithms/Sorting/closest-numbers.cpp +++ b/Algorithms/Sorting/closest-numbers.cpp @@ -1,43 +1,97 @@ -//closest-numbers.cpp -//Closest Numbers -//Algorithms - Search -//Author: derekhh - -#include -#include -#include -#include +#include + using namespace std; -int a[200000]; +vector split_string(string); + +// Complete the closestNumbers function below. +vector closestNumbers(vector arr) { + + sort(arr.begin(),arr.end()); + int small=(arr[1]-arr[0]); + for(int i=1;i(arr[i]-arr[i-1])){ + small=(arr[i]-arr[i-1]); + } + } + cout< ret; + for(int i=1;i ansv; +} int main() { - int n; - cin >> n; - for (int i = 0; i < n; i++) - cin >> a[i]; - sort(a, a + n); - int ans = INT_MAX; - for (int i = 1; i < n; i++) - { - if (a[i] - a[i - 1] < ans) - { - ansv.clear(); - ans = a[i] - a[i - 1]; - ansv.push_back(a[i - 1]); - ansv.push_back(a[i]); - } - else if (a[i] - a[i - 1] == ans) - { - ansv.push_back(a[i - 1]); - ansv.push_back(a[i]); - } - } - for (int i = 0; i < (int)ansv.size(); i++) - cout << ansv[i] << " "; - cout << endl; - return 0; -} \ No newline at end of file + ofstream fout(getenv("OUTPUT_PATH")); + + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + string arr_temp_temp; + getline(cin, arr_temp_temp); + + vector arr_temp = split_string(arr_temp_temp); + + vector arr(n); + + for (int i = 0; i < n; i++) { + int arr_item = stoi(arr_temp[i]); + + arr[i] = arr_item; + } + + vector result = closestNumbers(arr); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +}