- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 38 lines of Java from the credited upstream file 462.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 minMoves2(int[] nums) {3 final int n = nums.length;4 final int median = quickSelect(nums, 0, n - 1, (n + 1) / 2);5 int ans = 0;6 7 for (final int num : nums)8 ans += Math.abs(num - median);9 10 return ans;11 }12 13 private int quickSelect(int[] nums, int l, int r, int k) {14 final int randIndex = new Random().nextInt(r - l + 1) + l;15 swap(nums, randIndex, r);16 final int pivot = nums[r];17 18 int nextSwapped = l;19 for (int i = l; i < r; ++i)20 if (nums[i] <= pivot)21 swap(nums, nextSwapped++, i);22 swap(nums, nextSwapped, r);23 24 final int count = nextSwapped - l + 1;25 if (count == k)26 return nums[nextSwapped];27 if (count > k)28 return quickSelect(nums, l, nextSwapped - 1, k);29 return quickSelect(nums, nextSwapped + 1, r, k - count);30 }31 32 private void swap(int[] nums, int i, int j) {33 final int temp = nums[i];34 nums[i] = nums[j];35 nums[j] = temp;36 }37}38