Java simple solution beat 83% using Arrays.sort with comments


  • 0
    B

    Original equation for the for loop part is

    int mid = nums[len / 2];
    for(int i = 0; i < len / 2; i++) {
           steps = steps + mid - nums[i] + nums[len - 1 - i] - mid;
     }
    

    So we don't need mid anymore, below is my solution

    public class Solution {
        public int minMoves2(int[] nums) {
            int steps = 0;
            int len = nums.length;
            Arrays.sort(nums);
            for(int i = 0; i < len / 2; i++) {
                steps = steps - nums[i] + nums[len - 1 - i]; 
            }
            return steps;
        }
    }
    

Log in to reply
 

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