Leetcode: The minimum number of moves makes the array elements equal | | "462"

Source: Internet
Author: User

Leetcode: The minimum number of moves makes the array elements equal | | "462" title description

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, with each move adding 1 or minus 1 to the selected element. You can assume that the array has a maximum length of 10000.

For example:

Input: [A] output:2 Description: only two actions are necessary (remember that each step only adds 1 or minus 1 to one of the elements): [three-to-one] and [2,2,3] = [  2,2,2]
Problem analysis

An intuitive understanding is this, if we have only two numbers, then what is the minimum number of steps we make them into equal elements? Of course, the difference between the two .

We know that the difference between the two is enough, as far as turning them into something doesn't really affect the outcome . For example, 1, 5, if the two are equal, can become 5, 5, 4, 4, and so on, the steps are 4 steps, that is, poor.

We just apply this logic to the two extreme elements of a sorted array. Once we are equal (no need to set explicitly, because we are just calculating), we discard the two outer, moving inward.

Java
   public int minMoves2 (int[] nums) {        arrays.sort (nums);        int i=0, j=nums.length-1, count=0;        while (I < j) {            count + = Nums[j]-nums[i];            ++i;            --j;        }        return count;    }

Leetcode: The minimum number of moves makes the array elements equal | | "462"

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.