- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 37 lines of Java from the credited upstream file 3224.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 minChanges(int[] nums, int k) {3 final int n = nums.length;4 final int pairSize = n / 2;5 int ans = n;6 Map<Integer, Integer> diffCount = new HashMap<>(); 7 8 9 int[] oneChangeCount = new int[k + 1];10 11 for (int i = 0; i < pairSize; ++i) {12 final int a = nums[i];13 final int b = nums[n - 1 - i];14 diffCount.merge(Math.abs(a - b), 1, Integer::sum);15 ++oneChangeCount[Math.max(Math.max(a, b), Math.max(k - a, k - b))];16 }17 18 19 20 21 int[] prefixOneChangeCount = oneChangeCount.clone();22 23 for (int i = k - 1; i >= 0; --i)24 prefixOneChangeCount[i] += prefixOneChangeCount[i + 1];25 26 for (Map.Entry<Integer, Integer> entry : diffCount.entrySet()) {27 final int diff = entry.getKey();28 final int freq = entry.getValue();29 final int oneChange = prefixOneChangeCount[diff] - freq;30 final int twoChanges = (pairSize - prefixOneChangeCount[diff]) * 2;31 ans = Math.min(ans, oneChange + twoChanges);32 }33 34 return ans;35 }36}37