首页 > 代码库 > Minimum Moves to Equal Array Elements
Minimum Moves to Equal Array Elements
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 is at most 10,000.
Example:
Input: [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2]
1 public class Solution { 2 public int minMoves2(int[] nums) { 3 Arrays.sort(nums); 4 5 int result = 0; 6 for (int i = 0, j = nums.length - 1; i < j; i++, j--) { 7 result += nums[j] - nums[i]; 8 } 9 return result; 10 } 11 }
Minimum Moves to Equal Array Elements
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。