-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
recover-the-original-array.cpp
39 lines (38 loc) · 1.04 KB
/
recover-the-original-array.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
// Time: O(n^2)
// Space: O(n)
class Solution {
public:
vector<int> recoverArray(vector<int>& nums) {
auto check = [&nums](int k, unordered_map<int, int> cnt, vector<int> *result) {
for (const auto& x : nums) {
if (cnt[x] == 0) {
continue;
}
if (cnt[x + 2 * k] == 0) {
return false;
}
--cnt[x];
--cnt[x + 2 * k];
result->emplace_back(x + k);
}
return true;
};
sort(begin(nums), end(nums));
unordered_map<int, int> cnt;
for (const auto& x : nums) {
++cnt[x];
}
for (int i = 1; i <= size(nums) / 2; ++i) {
int k = nums[i] - nums[0];
if (k == 0 || k % 2) {
continue;
}
k /= 2;
vector<int> result;
if (check(k, cnt, &result)) {
return result;
}
}
return {};
}
};