Skip to content

Commit e93783d

Browse files
authored
Create recover-the-original-array.cpp
1 parent 96f5593 commit e93783d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

C++/recover-the-original-array.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> recoverArray(vector<int>& nums) {
7+
auto check = [&nums](int k, unordered_map<int, int> cnt, vector<int> *result) {
8+
for (const auto& x : nums) {
9+
if (cnt[x] == 0) {
10+
continue;
11+
}
12+
if (cnt[x + 2 * k] == 0) {
13+
return false;
14+
}
15+
--cnt[x];
16+
--cnt[x + 2 * k];
17+
result->emplace_back(x + k);
18+
}
19+
return true;
20+
};
21+
sort(begin(nums), end(nums));
22+
unordered_map<int, int> cnt;
23+
for (const auto& x : nums) {
24+
++cnt[x];
25+
}
26+
for (int i = 1; i <= size(nums) / 2; ++i) {
27+
int k = nums[i] - nums[0];
28+
if (k == 0 || k % 2) {
29+
continue;
30+
}
31+
k /= 2;
32+
vector<int> result;
33+
if (check(k, cnt, &result)) {
34+
return result;
35+
}
36+
}
37+
return {};
38+
}
39+
};

0 commit comments

Comments
 (0)