Https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/
Package COM. company; import Java. util. *; // The https://discuss.leetcode.com/topic/68736/java-just-like-meeting-point-problem// above is the overall solution, and the median can be obtained (just like meeting point problem) // The solution above the https://discuss.leetcode.com/topic/68758/java-o-n-time-using-quickselect/2// is O (n) method for obtaining the median (in fact, the method for obtaining the K-bit result, quick-select) Class solution {// corresponds to the first method above public int minmoves2_old (INT [] Nums) {arrays. sort (Nums); int I = 0, j = nums. length-1; int ret = 0; while (I <j) {RET + = Nums [J]-nums [I]; I ++; j --;} return ret;} // corresponding to the second method above public int minmoves2 (INT [] Nums) {int mid = getpos (Nums, Nums. length/2 + 1, 0, Nums. length-1); int ret = 0; For (INT I = 0; I <nums. length; I ++) {RET + = math. ABS (Nums [I]-mid);} return ret;} private int getpos (INT [] Nums, int K, int start, int end) {int end = Nums [end]; int L EFT = start; int right = end; while (left <= right) {While (left <= Right & Nums [left] <distinct) left ++; while (left <= Right & Nums [right]> = Break) Right --; If (left> right) {break;} swap (Nums, left, right );} swap (Nums, left, end); If (k = left + 1) {return Nums [left];} If (k <left + 1) {return getpos (Nums, k, start, left-1);} else {return getpos (Nums, K, left + 1, end);} private void Swap (INT [] Nums, int A, int B) {int TMP = Nums [a]; Nums [a] = Nums [B]; nums [B] = TMP;} public class main {public static void main (string [] ARGs) throws interruptedexception {system. out. println ("Hello! "); Solution = new solution (); // your CODEC object will be instantiated and called as such: int [] Nums = {1, 2, 3}; int ret = solution. minmoves2 (Nums); system. out. printf ("RET: % d \ n", RET); system. out. println ();}}
Minimum-moves-to-Equal-array-elements-II (good)