JAVA Simple solution ,very easy to understand!!


  • 0
    J

    My Solution is not very fast,but it can make you clear about this question.
    Supposing mid is the element of the final equal array which can make the minimum moves.
    For example,nums={1,2,89,10086} mid can be any number in [2,89]. if nums={1,4,7} mid is 4. So,the question is getting the middle element of an sorted array.

    class Solution {
    	public int minMoves2(int[] nums) {
    		Arrays.sort(nums);
    		int mid = nums[nums.length / 2], count = 0;
    		for (int num : nums)
    			count += Math.abs(num - mid);
    		return count;
    	}
    }
    

    Sorry for my poor English.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.