(Java) LeetCode 453. Minimum Moves to Equal Array Elements —— 最小移動次數使數組元素相等

來源:互聯網
上載者:User

標籤:xpl   最小數   tput   次數   style   推理   red   數組   就是   

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

Example:

Input:[1,2,3]Output:3Explanation:Only three moves are needed (remember each move increments two elements):[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

 

覺得和“演算法”知識無關的簡單題反而有點難度啊……首先固定了每次都要使得n-1個元素+1,那麼這n-1個一定是最小的n-1個,否則就會越加越多。每次都找最小的n-1個去加,直到所有的數相等。換個角度,就等於每次找到最大的那個數使得其-1,直到最大和最小的數相等。最終,所有比最小的那個數大的數,都要變成最小的數。所以,結果就是求所有數與最小數差的和。即,所有數的和與最小數與數組長度乘積的差。本題就是個邏輯推理和數學式的簡化。感覺演算法有的時候就是數學競賽啊……

 

Java

class Solution {    public int minMoves(int[] nums) {        int min = nums[0], sum = 0;        for (int num : nums) {            if (num < min)                min = num;            sum += num;        }        return sum - nums.length * min;    }}

 

(Java) LeetCode 453. Minimum Moves to Equal Array Elements —— 最小移動次數使數組元素相等

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.