462. Minimum Moves to Equal array Elements II min move to equal array element II

Source: Internet
Author: User

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, wher E a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array ' s length are at 10,000.

Example:

Input: [A] Output:2Explanation:only moves is needed (remember each move increments or decrements one element): [A]  =  [2,2,3]  =  [2,2,2]

given an array of non-empty integers, find the minimum number of moves required to make all array elements equal, move the selected element by 1 or decrement the selected element by 1.
  
 
  1. /**
  2. * @param {number[]} nums
  3. * @return {number}
  4. */
  5. var minMoves2 = function(nums) {
  6. let newNums = nums.sort((a,b)=>{return a-b});
  7. let mid = nums[parseInt(newNums.length / 2)];
  8. let sum = 0;
  9. for(let i in newNums){
  10. sum += Math.abs(newNums[i] - mid);
  11. }
  12. return sum;
  13. };



From for notes (Wiz)

462. Minimum Moves to Equal array Elements II min move to equal array element II

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.