[JAVA] Sort and find median / T : O(NLogN), S : O(1)


  • 0
    J
    public class Solution {
        // If min(sum((x-ai)^2) ==> x = (a1 + ... + aN) / N
        // If min(sum(Math.abs(x-ai)) ==> median of array.
        public int minMoves2(int[] nums) {
            Arrays.sort(nums);
            int median = nums[nums.length/2];
            int sum = 0;
            for(int num : nums){
                sum += Math.abs(num - median);
            }
            return sum;
        }
    }
    

Log in to reply
 

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