forked from deepaktalwardt/interview-prep-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmallest-difference.cpp
More file actions
36 lines (35 loc) · 881 Bytes
/
smallest-difference.cpp
File metadata and controls
36 lines (35 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <vector>
#include <algorithm>
#include <limits>
#include <iostream>
using namespace std;
vector<int> smallestDifference(vector<int> arrayOne, vector<int> arrayTwo) {
// Write your code here.
vector<int> result;
sort(arrayOne.begin(), arrayOne.end());
sort(arrayTwo.begin(), arrayTwo.end());
int numOne, numTwo;
int minSoFar = numeric_limits<int>::max();
int i = 0;
int j = 0;
int currDiff = numeric_limits<int>::max();
while (i < arrayOne.size() && j < arrayTwo.size()) {
numOne = arrayOne[i];
numTwo = arrayTwo[j];
if (numOne < numTwo) {
currDiff = numTwo - numOne;
i++;
} else if (numOne > numTwo) {
currDiff = numOne - numTwo;
j++;
} else {
result = {numOne, numTwo};
return result;
}
if (currDiff < minSoFar) {
minSoFar = currDiff;
result = {numOne, numTwo};
}
}
return result;
}