Thinking (assuming that each array have been sorted)
- Or less so that each maximum number n-1 plus 1, times out direct violence Solution
- Improved First: In order to make the smallest element is equal to the largest element, at least array maximum - minimum time, so in order to solve the violence (see below first python code) based again
- Improved II: whole solution process is the smallest ever catch maximum, until the two are equal so far. \ (max_ {0} \) is the maximum value of the original array, the updated \ (max_ {1} \) of the original array of the n-1 plus the last \ ((max-min) \ ) , \ (max_ {2} \) of the original array of n-2-th plus the last \ ((min-max) \) ... and can be found in every min is the last max,
- The final number of movements is \ (moves = \ sum_ {i = 1} ^ {n-1} (a [i] -a [0]) \) where n is the length of the array
# 暴力求解 -> 超时
class Solution:
def minMoves(self, nums) -> int:
nums = sorted(nums)
if len(nums) == 2:
return nums[1]-nums[0]
if len(nums) == 1 or len(nums) == 0:
return 0
if nums[0] == nums[-2]:
return nums[-1] - nums[0]
# 达到目的必然会移动不少于max-min步, 因为最后的结果的max一定是大于原有max的, 所以min至少要先移动到原有max那里去
count = nums[-1]-nums[0]
for i in range(len(nums) - 1):
nums[i] += count
nums = sorted(nums)
while nums[0] != nums[-1]:
for i in range(len(nums)-1):
nums[i] += 1
count += 1
nums = sorted(nums)
return count
# 学习官方求解 修改后的 -> 通过
# 其实优化过程, 就是个找规律的过程
class Solution:
def minMoves(self, nums):
sums = sum(nums)
mins = min(nums)
mul = mins*len(nums)
return sums - mul
to sum up
If I could find the law, it is not optimized thing