Java median solution


  • 0
    D
    public class Solution {
        public int minMoves2(int[] nums) {
            if (nums == null || nums.length <= 1) {
                return 0;
            }
            Arrays.sort(nums);
            int n = nums.length;
            int median = (nums[(n - 1) / 2] + nums[n / 2]) / 2;
            int ret = 0;
            for (int num : nums) {
                ret += Math.abs(median - num);
            }
            return ret;
        }
    }
    

Log in to reply
 

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