Share my solution with explanation


  • 0
    L

    Considering such an array [1, 102], the minimum moves is 101, achieved by moving 1 and 102 towards a random value between 1 and 102(both inclusive). Because if you choose a value X bigger than 102 or smaller than 1, the moves will be
    101 + (X - 102) or 101 + (1 - X).
    So for random array like [1, 3, 4, 78, 100, 102], we shall choose a median value between 4 and 78.

    public int minMoves2(int[] nums) {
            if(nums == null || nums.length <= 1)
                return 0;
            Arrays.sort(nums);
            int length = nums.length;
            int i = 0, j = 0;
            if(length % 2 == 0){
                j = length / 2;
                i = j - 1;
            }else{
                j = length / 2 + 1;
                i = length / 2 - 1;
            }
            int res = 0;
            for(;i >= 0 && j < length ; i--, j++){
                res += nums[j] - nums[i];
            }
            return res;
        }
    

Log in to reply
 

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