Minimum-moves-to-Equal-array-elements-II (good)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.