-
Notifications
You must be signed in to change notification settings - Fork 26
/
smallest-diff.cpp
73 lines (62 loc) · 1.51 KB
/
smallest-diff.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
// T.C - O(Nlog(N) + Mlog(M) + N + M) ==> )(N(logN) + Mlog(M))
// Sorting for A of length A and B of length is Nlog(N) + Mlog(M) +
// Two pointer logic, we are just iterating over the array once => N + M
// S.C - O(1) because we are sorting the array in place and we're not storing any additional memory.
int main(int argc, char* argv[]) {
abhisheknaiidu();
vector<int> nums1{-1,5,10,20,28,3};
vector<int> nums2{26,134,135,15,17};
vector<int> ans;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int index1 = 0;
int index2 = 0;
int current = INT_MAX;
int smaller = INT_MAX;
while(index1 < nums1.size() && index2 < nums2.size()) {
int first = nums1[index1];
int second = nums2[index2];
if(first < second ) {
current = second - first;
index1++;
}
else if(second < first) {
current = first - second;
index2++;
}
else {
// return vector<int> {first, second};
}
if(smaller > current) {
smaller = current;
ans = {first, second};
}
}
for(auto x: ans) {
cout << x << " ";
}
return 0;
}