Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 91 additions & 37 deletions Algorithms/Sorting/closest-numbers.cpp
Original file line number Diff line number Diff line change
@@ -1,43 +1,97 @@
//closest-numbers.cpp
//Closest Numbers
//Algorithms - Search
//Author: derekhh

#include<iostream>
#include<algorithm>
#include<climits>
#include<vector>
#include <bits/stdc++.h>

using namespace std;

int a[200000];
vector<string> split_string(string);

// Complete the closestNumbers function below.
vector<int> closestNumbers(vector<int> arr) {

sort(arr.begin(),arr.end());
int small=(arr[1]-arr[0]);
for(int i=1;i<arr.size();i++){

if(small>(arr[i]-arr[i-1])){
small=(arr[i]-arr[i-1]);
}
}
cout<<small;
vector<int> ret;
for(int i=1;i<arr.size();i++){
if((arr[i]-arr[i-1])==small){
ret.push_back(arr[i-1]);
ret.push_back(arr[i]);

}
}

return ret;

vector<int> 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;
}
ofstream fout(getenv("OUTPUT_PATH"));

int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');

string arr_temp_temp;
getline(cin, arr_temp_temp);

vector<string> arr_temp = split_string(arr_temp_temp);

vector<int> arr(n);

for (int i = 0; i < n; i++) {
int arr_item = stoi(arr_temp[i]);

arr[i] = arr_item;
}

vector<int> 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<string> 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<string> 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;
}