O(n logn) Java Simple Solution with Median

  • 1

    We can find a median by sorting the array (although there is at least one more efficient way to do it) and just calculate the number of moves:

    public class Solution {
        public int minMoves2(int[] nums) {
            if (nums == null || nums.length <= 1) return 0;
            int median = nums[nums.length/2], moves = 0;
            for (int num : nums)
                moves += Math.abs(num - median);
            return moves;

Log in to reply

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