問題:
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:Input:
[1,2,3]
Output:
2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]
大意:
給出一個非空整型數(shù)組,找到需要移動的最小值來讓數(shù)組的所有元素都相等儒拂,一次移動是指將指定元素加一或者減一搞监。
你可以假設(shè)數(shù)組的長度不超過10000绒疗。
例子:輸入:
[1,2,3]
輸出:
2
解釋:
只需要兩次移動(記住每次移動是指增減一個元素):
[1,2,3] => [2,2,3] => [2,2,2]
思路:
題目的描述有一點誤導(dǎo)性,主要是用了“移動”這個詞衷旅,而且給出的例子也不夠明確,一開始我誤以為是要將元素進行位移,導(dǎo)致想的很復(fù)雜较店,后來才發(fā)現(xiàn)是對元素進行加減。
只是加減就很簡單了容燕,我們要通過最小的加減數(shù)來使所有的元素都相同梁呈,最快的方式是往中間靠攏,這就需要先給數(shù)組排序蘸秘,然后取其中間的數(shù)官卡,由于每次“移動”都只能加一或者減一,所以“移動”的次數(shù)其實就是兩數(shù)之間的差值醋虏。這樣遍歷一次都進行一次減法就行了寻咒,當然要記得取絕對值。
代碼(Java):
public class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int middle = nums[nums.length/2];
int result = 0;
for (int i = 0; i < nums.length; i++) {
result += Math.abs(middle - nums[i]);
}
return result;
}
}
他山之石:
public class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int i = 0, j = nums.length-1;
int count = 0;
while(i < j){
count += nums[j]-nums[i];
i++;
j--;
}
return count;
}
}
同樣的思路颈嚼,這種做法理想情況下會快一半毛秘。
合集:https://github.com/Cloudox/LeetCode-Record