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
- 39 lines of Java from the credited upstream file 2122.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 int[] recoverArray(int[] nums) {3 final int n = nums.length;4 Map<Integer, Integer> count = new HashMap<>();5 6 for (final int num : nums)7 count.merge(num, 1, Integer::sum);8 9 Arrays.sort(nums);10 11 for (int i = 1; i < n; ++i) {12 final int x = nums[i] - nums[0]; 13 if (x <= 0 || x % 2 == 1)14 continue;15 Map<Integer, Integer> countCopy = new HashMap<>();16 countCopy.putAll(count);17 int[] arr = getArray(nums, x, countCopy);18 if (arr.length == n / 2)19 return arr;20 }21 22 throw new IllegalarrrgumentException();23 }24 25 private int[] getArray(int[] nums, int x, Map<Integer, Integer> count) {26 List<Integer> arr = new ArrayList<>();27 for (final int num : nums) {28 if (count.getOrDefault(num, 0) == 0)29 continue;30 if (count.getOrDefault(num + x, 0) == 0)31 return new int[] {};32 count.merge(num, -1, Integer::sum);33 count.merge(num + x, -1, Integer::sum);34 arr.add(num + x / 2);35 }36 return arr.stream().mapToInt(Integer::intValue).toArray();37 }38}39