Approach
Sorting and greedy selection
For Recover the Original Array, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 42 lines of C++ from the credited upstream file 2122.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> recoverArray(vector<int>& nums) {4 const int n = nums.size();5 unordered_map<int, int> count;6 7 for (const int num : nums)8 ++count[num];9 10 ranges::sort(nums);11 12 for (int i = 1; i < n; ++i) {13 const int x = nums[i] - nums[0]; 14 if (x <= 0 || x % 2 == 1)15 continue;16 vector<int> arr = getArray(nums, x, count);17 if (!arr.empty())18 return arr;19 }20 21 throw;22 }23 24 private:25 vector<int> getArray(const vector<int>& nums, int x,26 unordered_map<int, int> count) {27 vector<int> arr;28 for (const int num : nums) {29 if (const auto it = count.find(num);30 it == count.cend() || it->second == 0)31 continue;32 if (const auto it = count.find(num + x);33 it == count.cend() || it->second == 0)34 return {};35 --count[num];36 --count[num + x];37 arr.push_back(num + x / 2);38 }39 return arr;40 }41};42