Approach
Sorting and greedy selection
For Find Array Given Subset Sums, 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
- 43 lines of Java from the credited upstream file 1982.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 1 loop block 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 n, int[] sums) {3 Arrays.sort(sums);4 return recover(sums).stream().mapToInt(Integer::intValue).toArray();5 }6 7 private List<Integer> recover(int[] sums) {8 if (sums.length == 1) 9 return new ArrayList<>();10 11 Map<Integer, Long> count = Arrays.stream(sums).boxed().collect(12 Collectors.groupingBy(Function.identity(), Collectors.counting()));13 14 15 16 17 final int num = sums[1] - sums[0];18 int i = 0; 19 int[] sumsExcludingNum = new int[sums.length / 2];20 int[] sumsIncludingNum = new int[sums.length / 2];21 boolean chooseSumsIncludingNum = false;22 23 for (final int sum : sums) {24 if (count.get(sum) == 0)25 continue;26 count.merge(sum, -1L, Long::sum);27 count.merge(sum + num, -1L, Long::sum);28 sumsExcludingNum[i] = sum;29 sumsIncludingNum[i] = sum + num;30 ++i;31 if (sum + num == 0)32 chooseSumsIncludingNum = true;33 }34 35 36 37 38 List<Integer> recovered = recover(chooseSumsIncludingNum ? sumsIncludingNum : sumsExcludingNum);39 recovered.add(chooseSumsIncludingNum ? -num : num);40 return recovered;41 }42}43