Leetcode 462. Minimum Moves to Equal Array Elements II

Source: Internet
Author: User

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where 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:[1,2,3]output:2explanation:only moves is needed (remember each move increments or decrements one element): [1, 2, 3]  =  [2,2,3]  [  2,2,2]

"Thinking Analysis"

This topic is similar to the minimum Moves to Equal Array elements. In the previous topic, we changed the idea of solving a problem by converting an operation that adds 1 on the number of n-1 to one operation per number, until each number is reduced to its minimum value. In this topic each of our operations is a number in the array plus 1 or minus 1, until all the numbers are the same. One idea is that the larger number decreases, and the smaller number increases until they are equal to the median value.

1. First sort the array

2. Find mid-value mid

3. Iterate through the array to find the Nums[i]-mid and

Because there is no guarantee that the number of array elements is odd, there is not necessarily an intermediate value. The general solution is as follows:

1. First sort the array

2. Match the number 22, and find out the sum of their difference.

The code is as follows:

1  Public classSolution {2      Public intMinMoves2 (int[] nums) {3 Arrays.sort (nums);4         inti = 0, j = nums.length-1;5         intCount = 0;6          while(I <j) {7Count + = nums[j--]-nums[i++];8         }9         Ten         returncount; One     } A}

Leetcode 462. Minimum Moves to Equal Array Elements 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.