O(n) solution (without using the sum idea)


  • 0
    public int minMoves(int[] nums) {
            int min = 0;
           // get the minimum element
            for(int i = 1; i < nums.length; i++)
                min = nums[i] < nums[min] ? i : min;
            // swap it with first element in array
            int tmp = nums[min];
            nums[min] = nums[0];
            nums[0] = tmp;
            int moves = 0;
            // accumulate the difference between each element and min
            for(int i = 1; i < nums.length; i++)
                moves += nums[i] - nums[0];
            return moves;
        }
    

Log in to reply
 

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