Clean java solution. O(n log n) time


  • 1
    P
        public int minMoves2(int[] nums) {
            Arrays.sort(nums);
    
            int length = nums.length;
            int halfLength = length>>1;
            int median = nums[halfLength];
    
            int numberOfMoves = 0;
    
            for (int i = 0; i < halfLength; i++) {
                numberOfMoves += median - nums[i];
                numberOfMoves += nums[length - i - 1] - median;
            }
    
            return numberOfMoves;
        }
    

    You can see that addition and subtraction of the median occur the same amount of time, so we can make it shorter.

        public int minMoves2(int[] nums) {
            Arrays.sort(nums);
    
            int length = nums.length;
            int halfLength = length>>1;
    
            int numberOfMoves = 0;
    
            for (int i = 0; i < halfLength; i++) {
                numberOfMoves -= nums[i];
                numberOfMoves += nums[length - i - 1];
            }
    
            return numberOfMoves;
        }
    

Log in to reply
 

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